home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / xulrunner-1.9.0.14 / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2009-09-02  |  107.1 KB  |  3,258 lines

  1. //@line 44 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_IDLETIME            = "app.update.idletime";
  10. const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
  11. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  12. const PREF_APP_UPDATE_URL                 = "app.update.url";
  13. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  14. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  15. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  16. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  17. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  18. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  19. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  20. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never.";
  21. const PREF_PARTNER_BRANCH                 = "app.partner.";
  22. const PREF_APP_DISTRIBUTION               = "distribution.id";
  23. const PREF_APP_DISTRIBUTION_VERSION       = "distribution.version";
  24.  
  25. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  26. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  27. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  28. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  29. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  30.  
  31. const KEY_GREDIR          = "GreD";
  32. const KEY_APPDIR          = "XCurProcD";
  33. //@line 79 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  34.  
  35. const DIR_UPDATES         = "updates";
  36. const FILE_UPDATE_STATUS  = "update.status";
  37. const FILE_UPDATE_VERSION = "update.version";
  38. const FILE_UPDATE_ARCHIVE = "update.mar";
  39. const FILE_UPDATE_LOG     = "update.log"
  40. const FILE_UPDATES_DB     = "updates.xml";
  41. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  42. const FILE_PERMS_TEST     = "update.test";
  43. const FILE_LAST_LOG       = "last-update.log";
  44. const FILE_UPDATER_INI    = "updater.ini";
  45.  
  46. const MODE_RDONLY   = 0x01;
  47. const MODE_WRONLY   = 0x02;
  48. const MODE_CREATE   = 0x08;
  49. const MODE_APPEND   = 0x10;
  50. const MODE_TRUNCATE = 0x20;
  51.  
  52. const PERMS_FILE      = 0644;
  53. const PERMS_DIRECTORY = 0755;
  54.  
  55. const STATE_NONE            = "null";
  56. const STATE_DOWNLOADING     = "downloading";
  57. const STATE_PENDING         = "pending";
  58. const STATE_APPLYING        = "applying";
  59. const STATE_SUCCEEDED       = "succeeded";
  60. const STATE_DOWNLOAD_FAILED = "download-failed";
  61. const STATE_FAILED          = "failed";
  62.  
  63. // From updater/errors.h:
  64. const WRITE_ERROR = 7;
  65.  
  66. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  67. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  68. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  69.  
  70. const TOOLKIT_ID              = "toolkit@mozilla.org";
  71.  
  72. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  73.  
  74. const nsIExtensionManager     = Components.interfaces.nsIExtensionManager;
  75. const nsILocalFile            = Components.interfaces.nsILocalFile;
  76. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  77. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  78. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  79. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  80. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  81. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  82. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  83. const nsIINIParserFactory     = Components.interfaces.nsIINIParserFactory;
  84.  
  85. const Node = Components.interfaces.nsIDOMNode;
  86.  
  87. var gApp        = null;
  88. var gPref       = null;
  89. var gABI        = null;
  90. var gOSVersion  = null;
  91. var gLocale     = null;
  92. var gConsole    = null;
  93. var gLogEnabled = { };
  94.  
  95. // shared code for suppressing bad cert dialogs
  96. //@line 40 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/shared/src/badCertHandler.js"
  97.  
  98. /**
  99.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  100.  */
  101. function checkCert(channel) {
  102.   if (!channel.originalURI.schemeIs("https"))  // bypass
  103.     return;
  104.  
  105.   const Ci = Components.interfaces;  
  106.   var cert =
  107.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  108.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  109.  
  110.   var issuer = cert.issuer;
  111.   while (issuer && !cert.equals(issuer)) {
  112.     cert = issuer;
  113.     issuer = cert.issuer;
  114.   }
  115.  
  116.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  117.     throw "cert issuer is not built-in";
  118. }
  119.  
  120. /**
  121.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  122.  * security dialogs from being shown to the user.  It is better to simply fail
  123.  * if the certificate is bad. See bug 304286.
  124.  */
  125. function BadCertHandler() {
  126. }
  127. BadCertHandler.prototype = {
  128.  
  129.   // nsIChannelEventSink
  130.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  131.     // make sure the certificate of the old channel checks out before we follow
  132.     // a redirect from it.  See bug 340198.
  133.     checkCert(oldChannel);
  134.   },
  135.  
  136.   // Suppress any certificate errors
  137.   notifyCertProblem: function(socketInfo, status, targetSite) {
  138.     return true;
  139.   },
  140.  
  141.   // Suppress any ssl errors
  142.   notifySSLError: function(socketInfo, error, targetSite) {
  143.     return true;
  144.   },
  145.  
  146.   // nsIInterfaceRequestor
  147.   getInterface: function(iid) {
  148.     return this.QueryInterface(iid);
  149.   },
  150.  
  151.   // nsISupports
  152.   QueryInterface: function(iid) {
  153.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  154.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  155.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  156.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  157.         !iid.equals(Components.interfaces.nsISupports))
  158.       throw Components.results.NS_ERROR_NO_INTERFACE;
  159.     return this;
  160.   }
  161. };
  162. //@line 142 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  163.  
  164. /**
  165.  * Logs a string to the error console.
  166.  * @param   string
  167.  *          The string to write to the error console..
  168.  */
  169. function LOG(module, string) {
  170.   if (module in gLogEnabled || "all" in gLogEnabled) {
  171.     dump("*** " + module + ": " + string + "\n");
  172.     gConsole.logStringMessage(string);
  173.   }
  174. }
  175.  
  176. /**
  177.  * Convert a string containing binary values to hex.
  178.  */
  179. function binaryToHex(input) {
  180.   var result = "";
  181.   for (var i = 0; i < input.length; ++i) {
  182.     var hex = input.charCodeAt(i).toString(16);
  183.     if (hex.length == 1)
  184.       hex = "0" + hex;
  185.     result += hex;
  186.   }
  187.   return result;
  188. }
  189.  
  190. /**
  191.  * Gets a File URL spec for a nsIFile
  192.  * @param   file
  193.  *          The file to get a file URL spec to
  194.  * @returns The file URL spec to the file
  195.  */
  196. function getURLSpecFromFile(file) {
  197.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  198.                          .getService(Components.interfaces.nsIIOService);
  199.   var fph = ioServ.getProtocolHandler("file")
  200.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  201.   return fph.getURLSpecFromFile(file);
  202. }
  203.  
  204. /**
  205.  * Gets the specified directory at the specified hierarchy under a
  206.  * Directory Service key.
  207.  * @param   key
  208.  *          The Directory Service Key to start from
  209.  * @param   pathArray
  210.  *          An array of path components to locate beneath the directory
  211.  *          specified by |key|
  212.  * @return  nsIFile object for the location specified. If the directory
  213.  *          requested does not exist, it is created, along with any
  214.  *          parent directories that need to be created.
  215.  */
  216. function getDir(key, pathArray) {
  217.   return getDirInternal(key, pathArray, true, false);
  218. }
  219.  
  220. /**
  221.  * Gets the specified directory at the specified hierarchy under a
  222.  * Directory Service key.
  223.  * @param   key
  224.  *          The Directory Service Key to start from
  225.  * @param   pathArray
  226.  *          An array of path components to locate beneath the directory
  227.  *          specified by |key|
  228.  * @return  nsIFile object for the location specified. If the directory
  229.  *          requested does not exist, it is NOT created.
  230.  */
  231. function getDirNoCreate(key, pathArray) {
  232.   return getDirInternal(key, pathArray, false, false);
  233. }
  234.  
  235. /**
  236.  * Gets the specified directory at the specified hierarchy under the
  237.  * update root directory.
  238.  * @param   pathArray
  239.  *          An array of path components to locate beneath the directory
  240.  *          specified by |key|
  241.  * @return  nsIFile object for the location specified. If the directory
  242.  *          requested does not exist, it is created, along with any
  243.  *          parent directories that need to be created.
  244.  */
  245. function getUpdateDir(pathArray) {
  246.   return getDirInternal(KEY_APPDIR, pathArray, true, true);
  247. }
  248.  
  249. /**
  250.  * Gets the specified directory at the specified hierarchy under a
  251.  * Directory Service key.
  252.  * @param   key
  253.  *          The Directory Service Key to start from
  254.  * @param   pathArray
  255.  *          An array of path components to locate beneath the directory
  256.  *          specified by |key|
  257.  * @param   shouldCreate
  258.  *          true if the directory hierarchy specified in |pathArray|
  259.  *          should be created if it does not exist,
  260.  *          false otherwise.
  261.  * @param   update
  262.  *          true if finding the update directory,
  263.  *          false otherwise.
  264.  * @return  nsIFile object for the location specified.
  265.  */
  266. function getDirInternal(key, pathArray, shouldCreate, update) {
  267.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  268.                               .getService(Components.interfaces.nsIProperties);
  269.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  270. //@line 257 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  271.   for (var i = 0; i < pathArray.length; ++i) {
  272.     dir.append(pathArray[i]);
  273.     if (shouldCreate && !dir.exists())
  274.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  275.   }
  276.   return dir;
  277. }
  278.  
  279. /**
  280.  * Gets the file at the specified hierarchy under a Directory Service key.
  281.  * @param   key
  282.  *          The Directory Service Key to start from
  283.  * @param   pathArray
  284.  *          An array of path components to locate beneath the directory
  285.  *          specified by |key|. The last item in this array must be the
  286.  *          leaf name of a file.
  287.  * @return  nsIFile object for the file specified. The file is NOT created
  288.  *          if it does not exist, however all required directories along
  289.  *          the way are.
  290.  */
  291. function getFile(key, pathArray) {
  292.   var file = getDir(key, pathArray.slice(0, -1));
  293.   file.append(pathArray[pathArray.length - 1]);
  294.   return file;
  295. }
  296.  
  297. /**
  298.  * Gets the file at the specified hierarchy under the update root directory.
  299.  * @param   pathArray
  300.  *          An array of path components to locate beneath the directory
  301.  *          specified by |key|. The last item in this array must be the
  302.  *          leaf name of a file.
  303.  * @return  nsIFile object for the file specified. The file is NOT created
  304.  *          if it does not exist, however all required directories along
  305.  *          the way are.
  306.  */
  307. function getUpdateFile(pathArray) {
  308.   var file = getUpdateDir(pathArray.slice(0, -1));
  309.   file.append(pathArray[pathArray.length - 1]);
  310.   return file;
  311. }
  312.  
  313. /**
  314.  * Closes a Safe Output Stream
  315.  * @param   fos
  316.  *          The Safe Output Stream to close
  317.  */
  318. function closeSafeOutputStream(fos) {
  319.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  320.     try {
  321.       fos.finish();
  322.     }
  323.     catch (e) {
  324.       fos.close();
  325.     }
  326.   }
  327.   else
  328.     fos.close();
  329. }
  330.  
  331. /**
  332.  * Returns human readable status text from the updates.properties bundle
  333.  * based on an error code
  334.  * @param   code
  335.  *          The error code to look up human readable status text for
  336.  * @param   defaultCode
  337.  *          The default code to look up should human readable status text
  338.  *          not exist for |code|
  339.  * @returns A human readable status text string
  340.  */
  341. function getStatusTextFromCode(code, defaultCode) {
  342.   var sbs =
  343.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  344.       getService(Components.interfaces.nsIStringBundleService);
  345.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  346.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  347.   try {
  348.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  349.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  350.   }
  351.   catch (e) {
  352.     // Use the default reason
  353.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  354.   }
  355.   return reason;
  356. }
  357.  
  358. /**
  359.  * Get the Active Updates directory
  360.  * @param   key
  361.  *          The Directory Service Key (optional).
  362.  *          If used, don't search local appdata on Win32 and don't create dir.
  363.  * @returns The active updates directory, as a nsIFile object
  364.  */
  365. function getUpdatesDir(key) {
  366.   // Right now, we only support downloading one patch at a time, so we always
  367.   // use the same target directory.
  368.   var fileLocator =
  369.       Components.classes["@mozilla.org/file/directory_service;1"].
  370.       getService(Components.interfaces.nsIProperties);
  371.   var appDir;
  372.   if (key)
  373.     appDir = fileLocator.get(key, Components.interfaces.nsIFile);
  374.   else {
  375.     appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  376. //@line 368 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  377.   }
  378.   appDir.append(DIR_UPDATES);
  379.   appDir.append("0");
  380.   if (!appDir.exists() && !key)
  381.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  382.   return appDir;
  383. }
  384.  
  385. /**
  386.  * Reads the update state from the update.status file in the specified
  387.  * directory.
  388.  * @param   dir
  389.  *          The dir to look for an update.status file in
  390.  * @returns The status value of the update.
  391.  */
  392. function readStatusFile(dir) {
  393.   var statusFile = dir.clone();
  394.   statusFile.append(FILE_UPDATE_STATUS);
  395.   LOG("General", "Reading Status File: " + statusFile.path);
  396.   return readStringFromFile(statusFile) || STATE_NONE;
  397. }
  398.  
  399. /**
  400.  * Writes the current update operation/state to a file in the patch
  401.  * directory, indicating to the patching system that operations need
  402.  * to be performed.
  403.  * @param   dir
  404.  *          The patch directory where the update.status file should be
  405.  *          written.
  406.  * @param   state
  407.  *          The state value to write.
  408.  */
  409. function writeStatusFile(dir, state) {
  410.   var statusFile = dir.clone();
  411.   statusFile.append(FILE_UPDATE_STATUS);
  412.   writeStringToFile(statusFile, state);
  413. }
  414.  
  415. /**
  416. //@line 421 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  417.  */
  418. function writeVersionFile(dir, version) {
  419.   var versionFile = dir.clone();
  420.   versionFile.append(FILE_UPDATE_VERSION);
  421.   writeStringToFile(versionFile, version);
  422. }
  423.  
  424. /**
  425.  * Removes the Updates Directory
  426.  * @param   key
  427.  *          The Directory Service Key under which update directory resides
  428.  *          (optional).
  429.  */
  430. function cleanUpUpdatesDir(key) {
  431.   // Bail out if we don't have appropriate permissions
  432.   var updateDir;
  433.   try {
  434.     updateDir = getUpdatesDir(key);
  435.   }
  436.   catch (e) {
  437.     return;
  438.   }
  439.  
  440.   var e = updateDir.directoryEntries;
  441.   while (e.hasMoreElements()) {
  442.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  443.     // Preserve the last update log file for debugging purposes
  444.     if (f.leafName == FILE_UPDATE_LOG) {
  445.       try {
  446.         var dir = f.parent.parent;
  447.         var logFile = dir.clone();
  448.         logFile.append(FILE_LAST_LOG);
  449.         if (logFile.exists())
  450.           logFile.remove(false);
  451.         f.copyTo(dir, FILE_LAST_LOG);
  452.       }
  453.       catch (e) {
  454.         LOG("General", "Failed to copy file: " + f.path);
  455.       }
  456.     }
  457.     // Now, recursively remove this file.  The recusive removal is really
  458.     // only needed on Mac OSX because this directory will contain a copy of
  459.     // updater.app, which is itself a directory.
  460.     try {
  461.       f.remove(true);
  462.     }
  463.     catch (e) {
  464.       LOG("General", "Failed to remove file: " + f.path);
  465.     }
  466.   }
  467.   try {
  468.     updateDir.remove(false);
  469.   } catch (e) {
  470.     LOG("General", "Failed to remove update directory: " + updateDir.path +
  471.         " - This is almost always bad. Exception = " + e);
  472.     throw e;
  473.   }
  474. }
  475.  
  476. /**
  477.  * Clean up updates list and the updates directory.
  478.  * @param   key
  479.  *          The Directory Service Key under which update directory resides
  480.  *          (optional).
  481.  */
  482. function cleanupActiveUpdate(key) {
  483.   // Move the update from the Active Update list into the Past Updates list.
  484.   var um =
  485.       Components.classes["@mozilla.org/updates/update-manager;1"].
  486.       getService(Components.interfaces.nsIUpdateManager);
  487.   um.activeUpdate = null;
  488.   um.saveUpdates();
  489.  
  490.   // Now trash the updates directory, since we're done with it
  491.   cleanUpUpdatesDir(key);
  492. }
  493.  
  494. /**
  495.  * Gets a preference value, handling the case where there is no default.
  496.  * @param   func
  497.  *          The name of the preference function to call, on nsIPrefBranch
  498.  * @param   preference
  499.  *          The name of the preference
  500.  * @param   defaultValue
  501.  *          The default value to return in the event the preference has
  502.  *          no setting
  503.  * @returns The value of the preference, or undefined if there was no
  504.  *          user or default value.
  505.  */
  506. function getPref(func, preference, defaultValue) {
  507.   try {
  508.     return gPref[func](preference);
  509.   }
  510.   catch (e) {
  511.   }
  512.   return defaultValue;
  513. }
  514.  
  515. /**
  516.  * Gets the locale specified by the 'Locale' key in the 'Installation' section
  517.  * of updater.ini if it is available. Otherwise the general.useragent.locale
  518.  * preference is used to get the locale. It's possible for this preference to
  519.  * be localized, so we have to do a little extra work here. Similar code
  520.  * exists in nsHttpHandler.cpp when building the UA string.
  521.  */
  522. function getLocale() {
  523.   if (gLocale)
  524.     return gLocale;
  525.  
  526.   try {
  527. //@line 535 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  528.     var updaterIni = getFile(KEY_GREDIR, [FILE_UPDATER_INI]);
  529. //@line 537 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  530.     var iniParser = Components.classes["@mozilla.org/xpcom/ini-parser-factory;1"]
  531.                               .getService(nsIINIParserFactory).createINIParser(updaterIni);
  532.     gLocale = iniParser.getString("Installation", "Locale");
  533.     LOG("General", "Getting Locale from File: " + updaterIni.path + " Locale: " + gLocale);
  534.     return gLocale;
  535.   } catch (e) {}
  536.  
  537.   try {
  538.     // Get the default branch
  539.     var prefs = Components.classes["@mozilla.org/preferences-service;1"]
  540.         .getService(Components.interfaces.nsIPrefService);
  541.     var defaultPrefs = prefs.getDefaultBranch(null);
  542.     gLocale = defaultPrefs.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  543.   } catch (e) {
  544.     gLocale = gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  545.   }
  546.  
  547.   return gLocale;
  548. }
  549.  
  550. /**
  551.  * Read the update channel from defaults only.  We do this to ensure that
  552.  * the channel is tightly coupled with the application and does not apply
  553.  * to other instances of the application that may use the same profile.
  554.  */
  555. function getUpdateChannel() {
  556.   var channel = "default";
  557.   var prefName;
  558.   var prefValue;
  559.  
  560.   var defaults =
  561.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  562.       getDefaultBranch(null);
  563.   try {
  564.     channel = defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  565.   } catch (e) {
  566.     // use default when pref not found
  567.   }
  568.  
  569.   try {
  570.     var partners = gPref.getChildList(PREF_PARTNER_BRANCH, { });
  571.     if (partners.length) {
  572.       channel += "-cck";
  573.       partners.sort();
  574.  
  575.       for each (prefName in partners) {
  576.         prefValue = gPref.getCharPref(prefName);
  577.         channel += "-" + prefValue;
  578.       }
  579.     }
  580.   }
  581.   catch (e) {
  582.     Components.utils.reportError(e);
  583.   }
  584.  
  585.   return channel;
  586. }
  587.  
  588. /* Get the distribution pref values, from defaults only */
  589. function getDistributionPrefValue(aPrefName) {
  590.   var prefValue = "default";
  591.  
  592.   var defaults =
  593.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  594.       getDefaultBranch(null);
  595.   try {
  596.     prefValue = defaults.getCharPref(aPrefName);
  597.   } catch (e) {
  598.     // use default when pref not found
  599.   }
  600.  
  601.   return prefValue;
  602. }
  603.  
  604. /**
  605.  * An enumeration of items in a JS array.
  606.  * @constructor
  607.  */
  608. function ArrayEnumerator(aItems) {
  609.   this._index = 0;
  610.   if (aItems) {
  611.     for (var i = 0; i < aItems.length; ++i) {
  612.       if (!aItems[i])
  613.         aItems.splice(i, 1);
  614.     }
  615.   }
  616.   this._contents = aItems;
  617. }
  618.  
  619. ArrayEnumerator.prototype = {
  620.   _index: 0,
  621.   _contents: [],
  622.  
  623.   hasMoreElements: function() {
  624.     return this._index < this._contents.length;
  625.   },
  626.  
  627.   getNext: function() {
  628.     return this._contents[this._index++];
  629.   }
  630. };
  631.  
  632. /**
  633.  * Trims a prefix from a string.
  634.  * @param   string
  635.  *          The source string
  636.  * @param   prefix
  637.  *          The prefix to remove.
  638.  * @returns The suffix (string - prefix)
  639.  */
  640. function stripPrefix(string, prefix) {
  641.   return string.substr(prefix.length);
  642. }
  643.  
  644. /**
  645.  * Writes a string of text to a file.  A newline will be appended to the data
  646.  * written to the file.  This function only works with ASCII text.
  647.  */
  648. function writeStringToFile(file, text) {
  649.   var fos =
  650.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  651.       createInstance(nsIFileOutputStream);
  652.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  653.   if (!file.exists())
  654.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  655.   fos.init(file, modeFlags, PERMS_FILE, 0);
  656.   text += "\n";
  657.   fos.write(text, text.length);
  658.   closeSafeOutputStream(fos);
  659. }
  660.  
  661. /**
  662.  * Reads a string of text from a file.  A trailing newline will be removed
  663.  * before the result is returned.  This function only works with ASCII text.
  664.  */
  665. function readStringFromFile(file) {
  666.   var fis =
  667.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  668.       createInstance(nsIFileInputStream);
  669.   var modeFlags = MODE_RDONLY;
  670.   if (!file.exists())
  671.     return null;
  672.   fis.init(file, modeFlags, PERMS_FILE, 0);
  673.   var sis =
  674.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  675.       createInstance(Components.interfaces.nsIScriptableInputStream);
  676.   sis.init(fis);
  677.   var text = sis.read(sis.available());
  678.   sis.close();
  679.   if (text[text.length - 1] == "\n")
  680.     text = text.slice(0, -1);
  681.   return text;
  682. }
  683.  
  684. function getObserverService()
  685. {
  686.   return Components.classes["@mozilla.org/observer-service;1"]
  687.                    .getService(Components.interfaces.nsIObserverService);
  688. }
  689.  
  690. /**
  691.  * Update Patch
  692.  * @param   patch
  693.  *          A <patch> element to initialize this object with
  694.  * @throws if patch has a size of 0
  695.  * @constructor
  696.  */
  697. function UpdatePatch(patch) {
  698.   this._properties = {};
  699.   for (var i = 0; i < patch.attributes.length; ++i) {
  700.     var attr = patch.attributes.item(i);
  701.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  702.     switch (attr.name) {
  703.     case "selected":
  704.       this.selected = attr.value == "true";
  705.       break;
  706.     case "size":
  707.       if (0 == parseInt(attr.value)) {
  708.         LOG("UpdatePatch", "0-sized patch!");
  709.         throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  710.       }
  711.       // fall through
  712.     default:
  713.       this[attr.name] = attr.value;
  714.       break;
  715.     };
  716.   }
  717. }
  718. UpdatePatch.prototype = {
  719.   /**
  720.    * See nsIUpdateService.idl
  721.    */
  722.   serialize: function(updates) {
  723.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  724.     patch.setAttribute("type", this.type);
  725.     patch.setAttribute("URL", this.URL);
  726.     patch.setAttribute("hashFunction", this.hashFunction);
  727.     patch.setAttribute("hashValue", this.hashValue);
  728.     patch.setAttribute("size", this.size);
  729.     patch.setAttribute("selected", this.selected);
  730.     patch.setAttribute("state", this.state);
  731.  
  732.     for (var p in this._properties) {
  733.       if (this._properties[p].present)
  734.         patch.setAttribute(p, this._properties[p].data);
  735.     }
  736.  
  737.     return patch;
  738.   },
  739.  
  740.   /**
  741.    * A hash of custom properties
  742.    */
  743.   _properties: null,
  744.  
  745.   /**
  746.    * See nsIWritablePropertyBag.idl
  747.    */
  748.   setProperty: function(name, value) {
  749.     this._properties[name] = { data: value, present: true };
  750.   },
  751.  
  752.   /**
  753.    * See nsIWritablePropertyBag.idl
  754.    */
  755.   deleteProperty: function(name) {
  756.     if (name in this._properties)
  757.       this._properties[name].present = false;
  758.     else
  759.       throw Components.results.NS_ERROR_FAILURE;
  760.   },
  761.  
  762.   /**
  763.    * See nsIPropertyBag.idl
  764.    */
  765.   get enumerator() {
  766.     var properties = [];
  767.     for (var p in this._properties)
  768.       properties.push(this._properties[p].data);
  769.     return new ArrayEnumerator(properties);
  770.   },
  771.  
  772.   /**
  773.    * See nsIPropertyBag.idl
  774.    */
  775.   getProperty: function(name) {
  776.     if (name in this._properties &&
  777.         this._properties[name].present)
  778.       return this._properties[name].data;
  779.     throw Components.results.NS_ERROR_FAILURE;
  780.   },
  781.  
  782.   /**
  783.    * Returns whether or not the update.status file for this patch exists at the
  784.    * appropriate location.
  785.    */
  786.   get statusFileExists() {
  787.     var statusFile = getUpdatesDir();
  788.     statusFile.append(FILE_UPDATE_STATUS);
  789.     return statusFile.exists();
  790.   },
  791.  
  792.   /**
  793.    * See nsIUpdateService.idl
  794.    */
  795.   get state() {
  796.     if (this._properties.state)
  797.       return this._properties.state;
  798.     return STATE_NONE;
  799.   },
  800.   set state(val) {
  801.     this._properties.state = val;
  802.   },
  803.  
  804.   /**
  805.    * See nsISupports.idl
  806.    */
  807.   QueryInterface: function(iid) {
  808.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  809.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  810.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  811.         !iid.equals(Components.interfaces.nsISupports))
  812.       throw Components.results.NS_ERROR_NO_INTERFACE;
  813.     return this;
  814.   }
  815. };
  816.  
  817. /**
  818.  * Update
  819.  * Implements nsIUpdate
  820.  * @param   update
  821.  *          An <update> element to initialize this object with
  822.  * @throws if the update contains no patches
  823.  * @constructor
  824.  */
  825. function Update(update) {
  826.   this._properties = {};
  827.   this._patches = [];
  828.   this.installDate = 0;
  829.   this.isCompleteUpdate = false;
  830.   this.channel = "default"
  831.  
  832.   // Null <update>, assume this is a message container and do no
  833.   // further initialization
  834.   if (!update)
  835.     return;
  836.  
  837.   for (var i = 0; i < update.childNodes.length; ++i) {
  838.     var patchElement = update.childNodes.item(i);
  839.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  840.         patchElement.localName != "patch")
  841.       continue;
  842.  
  843.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  844.     try {
  845.       var patch = new UpdatePatch(patchElement);
  846.     } catch (e) {
  847.       continue;
  848.     }
  849.     this._patches.push(patch);
  850.   }
  851.  
  852.   if (0 == this._patches.length)
  853.     throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  854.  
  855.   for (var i = 0; i < update.attributes.length; ++i) {
  856.     var attr = update.attributes.item(i);
  857.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  858.     if (attr.name == "installDate" && attr.value)
  859.       this.installDate = parseInt(attr.value);
  860.     else if (attr.name == "isCompleteUpdate")
  861.       this.isCompleteUpdate = attr.value == "true";
  862.     else if (attr.name == "isSecurityUpdate")
  863.       this.isSecurityUpdate = attr.value == "true";
  864.     else if (attr.name == "detailsURL")
  865.       this._detailsURL = attr.value;
  866.     else if (attr.name == "channel")
  867.       this.channel = attr.value;
  868.     else
  869.       this[attr.name] = attr.value;
  870.   }
  871.  
  872.   // The Update Name is either the string provided by the <update> element, or
  873.   // the string: "<App Name> <Update App Version>"
  874.   var name = "";
  875.   if (update.hasAttribute("name"))
  876.     name = update.getAttribute("name");
  877.   else {
  878.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  879.                         .getService(Components.interfaces.nsIStringBundleService);
  880.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  881.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  882.     var appName = brandBundle.GetStringFromName("brandShortName");
  883.     name = updateBundle.formatStringFromName("updateName",
  884.                                              [appName, this.version], 2);
  885.   }
  886.   this.name = name;
  887. }
  888. Update.prototype = {
  889.   /**
  890.    * See nsIUpdateService.idl
  891.    */
  892.   get patchCount() {
  893.     return this._patches.length;
  894.   },
  895.  
  896.   /**
  897.    * See nsIUpdateService.idl
  898.    */
  899.   getPatchAt: function(index) {
  900.     return this._patches[index];
  901.   },
  902.  
  903.   /**
  904.    * See nsIUpdateService.idl
  905.    *
  906.    * We use a copy of the state cached on this object in |_state| only when
  907.    * there is no selected patch, i.e. in the case when we could not load
  908.    * |.activeUpdate| from the update manager for some reason but still have
  909.    * the update.status file to work with.
  910.    */
  911.   _state: "",
  912.   set state(state) {
  913.     if (this.selectedPatch)
  914.       this.selectedPatch.state = state;
  915.     this._state = state;
  916.     return state;
  917.   },
  918.   get state() {
  919.     if (this.selectedPatch)
  920.       return this.selectedPatch.state;
  921.     return this._state;
  922.   },
  923.  
  924.   /**
  925.    * See nsIUpdateService.idl
  926.    */
  927.   errorCode: 0,
  928.  
  929.   /**
  930.    * See nsIUpdateService.idl
  931.    */
  932.   get selectedPatch() {
  933.     for (var i = 0; i < this.patchCount; ++i) {
  934.       if (this._patches[i].selected)
  935.         return this._patches[i];
  936.     }
  937.     return null;
  938.   },
  939.  
  940.   /**
  941.    * See nsIUpdateService.idl
  942.    */
  943.   get detailsURL() {
  944.     if (!this._detailsURL) {
  945.       try {
  946.         // Try using a default details URL supplied by the distribution
  947.         // if the update XML does not supply one.
  948.         var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  949.                                   .getService(Components.interfaces.nsIURLFormatter);
  950.         return formatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
  951.       }
  952.       catch (e) {
  953.       }
  954.     }
  955.     return this._detailsURL || "";
  956.   },
  957.  
  958.   /**
  959.    * See nsIUpdateService.idl
  960.    */
  961.   serialize: function(updates) {
  962.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  963.     update.setAttribute("type", this.type);
  964.     update.setAttribute("name", this.name);
  965.     update.setAttribute("version", this.version);
  966.     update.setAttribute("platformVersion", this.platformVersion);
  967.     update.setAttribute("extensionVersion", this.extensionVersion);
  968.     update.setAttribute("detailsURL", this.detailsURL);
  969.     update.setAttribute("licenseURL", this.licenseURL);
  970.     update.setAttribute("serviceURL", this.serviceURL);
  971.     update.setAttribute("installDate", this.installDate);
  972.     update.setAttribute("statusText", this.statusText);
  973.     update.setAttribute("buildID", this.buildID);
  974.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  975.     update.setAttribute("channel", this.channel);
  976.     updates.documentElement.appendChild(update);
  977.  
  978.     for (var p in this._properties) {
  979.       if (this._properties[p].present)
  980.         update.setAttribute(p, this._properties[p].data);
  981.     }
  982.  
  983.     for (var i = 0; i < this.patchCount; ++i)
  984.       update.appendChild(this.getPatchAt(i).serialize(updates));
  985.  
  986.     return update;
  987.   },
  988.  
  989.   /**
  990.    * A hash of custom properties
  991.    */
  992.   _properties: null,
  993.  
  994.   /**
  995.    * See nsIWritablePropertyBag.idl
  996.    */
  997.   setProperty: function(name, value) {
  998.     this._properties[name] = { data: value, present: true };
  999.   },
  1000.  
  1001.   /**
  1002.    * See nsIWritablePropertyBag.idl
  1003.    */
  1004.   deleteProperty: function(name) {
  1005.     if (name in this._properties)
  1006.       this._properties[name].present = false;
  1007.     else
  1008.       throw Components.results.NS_ERROR_FAILURE;
  1009.   },
  1010.  
  1011.   /**
  1012.    * See nsIPropertyBag.idl
  1013.    */
  1014.   get enumerator() {
  1015.     var properties = [];
  1016.     for (var p in this._properties)
  1017.       properties.push(this._properties[p].data);
  1018.     return new ArrayEnumerator(properties);
  1019.   },
  1020.  
  1021.   /**
  1022.    * See nsIPropertyBag.idl
  1023.    */
  1024.   getProperty: function(name) {
  1025.     if (name in this._properties &&
  1026.         this._properties[name].present)
  1027.       return this._properties[name].data;
  1028.     throw Components.results.NS_ERROR_FAILURE;
  1029.   },
  1030.  
  1031.   /**
  1032.    * See nsISupports.idl
  1033.    */
  1034.   QueryInterface: function(iid) {
  1035.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  1036.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  1037.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  1038.         !iid.equals(Components.interfaces.nsISupports))
  1039.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1040.     return this;
  1041.   }
  1042. };
  1043.  
  1044. /**
  1045.  * UpdateService
  1046.  * A Service for managing the discovery and installation of software updates.
  1047.  * @constructor
  1048.  */
  1049. function UpdateService() {
  1050.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  1051.                     .getService(Components.interfaces.nsIXULAppInfo)
  1052.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  1053.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  1054.                     .getService(Components.interfaces.nsIPrefBranch2);
  1055.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  1056.                        .getService(Components.interfaces.nsIConsoleService);
  1057.  
  1058.   // Not all builds have a known ABI
  1059.   try {
  1060.     gABI = gApp.XPCOMABI;
  1061.   }
  1062.   catch (e) {
  1063.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  1064.   }
  1065.  
  1066.   var osVersion;
  1067.   var sysInfo = Components.classes["@mozilla.org/system-info;1"]
  1068.                           .getService(Components.interfaces.nsIPropertyBag2);
  1069.   try {
  1070.     osVersion = sysInfo.getProperty("name") + " " + sysInfo.getProperty("version");
  1071.   }
  1072.   catch (e) {
  1073.     LOG("UpdateService", "OS Version unknown: updates are not possible.");
  1074.   }
  1075.  
  1076.   if (osVersion) {
  1077.     try {
  1078.       osVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
  1079.     }
  1080.     catch (e) {
  1081.       // Not all platforms have a secondary widget library, so an error is nothing to worry about.
  1082.     }
  1083.     gOSVersion = encodeURIComponent(osVersion);
  1084.   }
  1085.  
  1086. //@line 1102 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1087.  
  1088.   // Start the update timer only after a profile has been selected so that the
  1089.   // appropriate values for the update check are read from the user's profile.
  1090.   var os = getObserverService();
  1091.  
  1092.   os.addObserver(this, "profile-after-change", false);
  1093.  
  1094.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid
  1095.   // shutdown leaks.
  1096.   os.addObserver(this, "xpcom-shutdown", false);
  1097. }
  1098.  
  1099. UpdateService.prototype = {
  1100.   /**
  1101.    * The downloader we are using to download updates. There is only ever one of
  1102.    * these.
  1103.    */
  1104.   _downloader: null,
  1105.  
  1106.   /**
  1107.    * Handle Observer Service notifications
  1108.    * @param   subject
  1109.    *          The subject of the notification
  1110.    * @param   topic
  1111.    *          The notification name
  1112.    * @param   data
  1113.    *          Additional data
  1114.    */
  1115.   observe: function(subject, topic, data) {
  1116.     var os = getObserverService();
  1117.  
  1118.     switch (topic) {
  1119.     case "profile-after-change":
  1120.       os.removeObserver(this, "profile-after-change");
  1121.       this._start();
  1122.       break;
  1123.     case "xpcom-shutdown":
  1124.       os.removeObserver(this, "xpcom-shutdown");
  1125.  
  1126.       // Release Services
  1127.       gApp      = null;
  1128.       gPref     = null;
  1129.       gConsole  = null;
  1130.       break;
  1131.     }
  1132.   },
  1133.  
  1134.   /**
  1135.    * Start the Update Service
  1136.    */
  1137.   _start: function() {
  1138.     // Start logging
  1139.     this._initLoggingPrefs();
  1140.  
  1141.     // Clean up any extant updates
  1142.     this._postUpdateProcessing();
  1143.  
  1144.     // Register a background update check timer
  1145.     var tm =
  1146.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  1147.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  1148.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  1149.     tm.registerTimer("background-update-timer", this, interval);
  1150.  
  1151.     // Resume fetching...
  1152.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1153.                         .getService(Components.interfaces.nsIUpdateManager);
  1154.     var activeUpdate = um.activeUpdate;
  1155.     if (activeUpdate) {
  1156.       var status = this.downloadUpdate(activeUpdate, true);
  1157.       if (status == STATE_NONE)
  1158.         cleanupActiveUpdate();
  1159.     }
  1160.   },
  1161.  
  1162.   /**
  1163.    * Perform post-processing on updates lingering in the updates directory
  1164.    * from a previous browser session - either report install failures (and
  1165.    * optionally attempt to fetch a different version if appropriate) or
  1166.    * notify the user of install success.
  1167.    */
  1168.   _postUpdateProcessing: function() {
  1169.     // Detect installation failures and notify
  1170.  
  1171.     // Bail out if we don't have appropriate permissions
  1172.     if (!this.canUpdate)
  1173.       return;
  1174.  
  1175.     var status = readStatusFile(getUpdatesDir());
  1176.  
  1177.     // Make sure to cleanup after an update that failed for an unknown reason
  1178.     if (status == "null")
  1179.       status = null;
  1180.  
  1181.     var updRootKey = null;
  1182. //@line 1219 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1183.  
  1184.     if (status == STATE_DOWNLOADING) {
  1185.       LOG("UpdateService", "_postUpdateProcessing: patch found in " +
  1186.           "downloading state");
  1187.     }
  1188.     else if (status != null) {
  1189.       // null status means the update.status file is not present, because either:
  1190.       // 1) no update was performed, and so there's no UI to show
  1191.       // 2) an update was attempted but failed during checking, transfer or
  1192.       //    verification, and was cleaned up at that point, and UI notifying of
  1193.       //    that error was shown at that stage.
  1194.       var um =
  1195.           Components.classes["@mozilla.org/updates/update-manager;1"].
  1196.           getService(Components.interfaces.nsIUpdateManager);
  1197.       var prompter =
  1198.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  1199.           createInstance(Components.interfaces.nsIUpdatePrompt);
  1200.  
  1201.       var shouldCleanup = true;
  1202.       var update = um.activeUpdate;
  1203.       if (!update) {
  1204.         update = new Update(null);
  1205.       }
  1206.       update.state = status;
  1207.       var sbs =
  1208.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  1209.           getService(Components.interfaces.nsIStringBundleService);
  1210.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1211.       if (status == STATE_SUCCEEDED) {
  1212.         update.statusText = bundle.GetStringFromName("installSuccess");
  1213.  
  1214.         // Update the patch's metadata.
  1215.         um.activeUpdate = update;
  1216.  
  1217.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  1218.         prompter.showUpdateInstalled(update);
  1219. //@line 1259 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1220.         // Perform platform-specific post-update processing.
  1221.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  1222.           Components.classes[POST_UPDATE_CONTRACTID].
  1223.               createInstance(Components.interfaces.nsIRunnable).run();
  1224.         }
  1225. //@line 1265 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1226.  
  1227.         // Done with this update. Clean it up.
  1228.         cleanupActiveUpdate(updRootKey);
  1229.       }
  1230.       else {
  1231.         // If we hit an error, then the error code will be included in the
  1232.         // status string following a colon.  If we had an I/O error, then we
  1233.         // assume that the patch is not invalid, and we restage the patch so
  1234.         // that it can be attempted again the next time we restart.
  1235.         var ary = status.split(": ");
  1236.         update.state = ary[0];
  1237.         if (update.state == STATE_FAILED && ary[1]) {
  1238.           update.errorCode = ary[1];
  1239.           if (update.errorCode == WRITE_ERROR) {
  1240.             prompter.showUpdateError(update);
  1241.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1242.             writeVersionFile(getUpdatesDir(), update.extensionVersion);
  1243.             return;
  1244.           }
  1245.         }
  1246.  
  1247.         // Something went wrong with the patch application process.
  1248.         cleanupActiveUpdate();
  1249.  
  1250.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1251.         var oldType = update.selectedPatch ? update.selectedPatch.type
  1252.                                            : "complete";
  1253.         if (update.selectedPatch && oldType == "partial") {
  1254.           // Partial patch application failed, try downloading the complete
  1255.           // update in the background instead.
  1256.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " +
  1257.               "failed, downloading Complete Patch and maybe showing UI");
  1258.           var status = this.downloadUpdate(update, true);
  1259.           if (status == STATE_NONE)
  1260.             cleanupActiveUpdate();
  1261.         }
  1262.         else {
  1263.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " +
  1264.               "only patch failed. Showing error.");
  1265.         }
  1266.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1267.         update.setProperty("patchingFailed", oldType);
  1268.         prompter.showUpdateError(update);
  1269.       }
  1270.     }
  1271.     else {
  1272.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1273.     }
  1274.   },
  1275.  
  1276.   /**
  1277.    * Initialize Logging preferences, formatted like so:
  1278.    *  app.update.log.<moduleName> = <true|false>
  1279.    */
  1280.   _initLoggingPrefs: function() {
  1281.     try {
  1282.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1283.                         .getService(Components.interfaces.nsIPrefService);
  1284.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1285.       var modules = logBranch.getChildList("", { value: 0 });
  1286.  
  1287.       for (var i = 0; i < modules.length; ++i) {
  1288.         if (logBranch.prefHasUserValue(modules[i]))
  1289.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1290.       }
  1291.     }
  1292.     catch (e) {
  1293.     }
  1294.   },
  1295.  
  1296.   /**
  1297.    * Notified when a timer fires
  1298.    * @param   timer
  1299.    *          The timer that fired
  1300.    */
  1301.   notify: function(timer) {
  1302.     // If a download is in progress, then do nothing.
  1303.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1304.       return;
  1305.  
  1306.     var self = this;
  1307.     var listener = {
  1308.       /**
  1309.        * See nsIUpdateService.idl
  1310.        */
  1311.       onProgress: function(request, position, totalSize) {
  1312.       },
  1313.  
  1314.       /**
  1315.        * See nsIUpdateService.idl
  1316.        */
  1317.       onCheckComplete: function(request, updates, updateCount) {
  1318.         self._selectAndInstallUpdate(updates);
  1319.       },
  1320.  
  1321.       /**
  1322.        * See nsIUpdateService.idl
  1323.        */
  1324.       onError: function(request, update) {
  1325.         LOG("Checker", "Error during background update: " + update.statusText);
  1326.       },
  1327.     }
  1328.     this.backgroundChecker.checkForUpdates(listener, false);
  1329.   },
  1330.  
  1331.   /**
  1332.    * Determine whether or not an update requires user confirmation before it
  1333.    * can be installed.
  1334.    * @param   update
  1335.    *          The update to be installed
  1336.    * @returns true if a prompt UI should be shown asking the user if they want
  1337.    *          to install the update, false if the update should just be
  1338.    *          silently downloaded and installed.
  1339.    */
  1340.   _shouldPrompt: function(update) {
  1341.     // There are two possible outcomes here:
  1342.     // 1. download and install the update automatically
  1343.     // 2. alert the user about the presence of an update before doing anything
  1344.     //
  1345.     // The outcome we follow is determined as follows:
  1346.     //
  1347.     // Note:  all Major updates require notification and confirmation
  1348.     //
  1349.     // Update Type      Mode      Incompatible    Outcome
  1350.     // Major            0         Yes or No       Notify and Confirm
  1351.     // Major            1         No              Notify and Confirm
  1352.     // Major            1         Yes             Notify and Confirm
  1353.     // Major            2         Yes or No       Notify and Confirm
  1354.     // Minor            0         Yes or No       Auto Install
  1355.     // Minor            1         No              Auto Install
  1356.     // Minor            1         Yes             Notify and Confirm
  1357.     // Minor            2         No              Auto Install
  1358.     // Minor            2         Yes             Notify and Confirm
  1359.     //
  1360.     // In addition, if there is a license associated with an update, regardless
  1361.     // of type it must be agreed to.
  1362.     //
  1363.     // If app.update.enabled is set to false, an update check is not performed
  1364.     // at all, and so none of the decision making above is entered into.
  1365.     //
  1366.     if (update.type == "major") {
  1367.       LOG("Checker", "_shouldPrompt: Prompting because it is a major update");
  1368.       return true;
  1369.     }
  1370.  
  1371.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1372.     try {
  1373.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1374.     }
  1375.     catch (e) {
  1376.       licenseAccepted = false;
  1377.     }
  1378.  
  1379.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1380.     if (!updateEnabled) {
  1381.       LOG("Checker", "_shouldPrompt: Not prompting because update is " +
  1382.           "disabled");
  1383.       return false;
  1384.     }
  1385.  
  1386.     // User has turned off automatic download and install
  1387.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1388.     if (!autoEnabled) {
  1389.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1390.       return true;
  1391.     }
  1392.  
  1393.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1394.     case 1:
  1395.       // Mode 1 is do not prompt only if there are no incompatibilities
  1396.       // releases
  1397.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1398.       return !isCompatible(update);
  1399.     case 2:
  1400.       // Mode 2 is do not prompt only if there are no incompatibilities
  1401.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1402.       return !isCompatible(update);
  1403.     }
  1404.     // Mode 0 is do not prompt regardless of incompatibilities
  1405.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1406.         "ignore incompatibilities");
  1407.     return false;
  1408.   },
  1409.  
  1410.   /**
  1411.    * Determine which of the specified updates should be installed.
  1412.    * @param   updates
  1413.    *          An array of available updates
  1414.    */
  1415.   selectUpdate: function(updates) {
  1416.     if (updates.length == 0)
  1417.       return null;
  1418.  
  1419.     // Choose the newest of the available minor and major updates.
  1420.     var majorUpdate = null, minorUpdate = null;
  1421.     var newestMinor = updates[0], newestMajor = updates[0];
  1422.  
  1423.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1424.                        .getService(Components.interfaces.nsIVersionComparator);
  1425.     for (var i = 0; i < updates.length; ++i) {
  1426.       if (updates[i].type == "major" &&
  1427.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1428.         majorUpdate = newestMajor = updates[i];
  1429.       if (updates[i].type == "minor" &&
  1430.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1431.         minorUpdate = newestMinor = updates[i];
  1432.     }
  1433.  
  1434.     // IMPORTANT
  1435.     // If there's a minor update, always try and fetch that one first,
  1436.     // otherwise use the newest major update.
  1437.     // selectUpdate() only returns one update.
  1438.     // if major were to trump minor, and we said "never" to the major
  1439.     // we'd never get the minor update, since selectUpdate()
  1440.     // would return the major update that the user said "never" to
  1441.     // (shadowing the important minor update with security fixes)
  1442.     return minorUpdate || majorUpdate;
  1443.   },
  1444.  
  1445.   /**
  1446.    * Determine which of the specified updates should be installed and
  1447.    * begin the download/installation process, optionally prompting the
  1448.    * user for permission if required.
  1449.    * @param   updates
  1450.    *          An array of available updates
  1451.    */
  1452.   _selectAndInstallUpdate: function(updates) {
  1453.     // Don't prompt if there's an active update - the user is already
  1454.     // aware and is downloading, or performed some user action to prevent
  1455.     // notification.
  1456.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1457.                        .getService(Components.interfaces.nsIUpdateManager);
  1458.     if (um.activeUpdate)
  1459.       return;
  1460.  
  1461.     var update = this.selectUpdate(updates, updates.length);
  1462.     if (!update)
  1463.       return;
  1464.  
  1465.     // check if the user said "never" to this version
  1466.     // this check is done here, and not in selectUpdate() so that
  1467.     // the user can get an upgrade they said "never" to if they
  1468.     // manually do "Check for Updates..."
  1469.     // note, selectUpdate() only returns one update.
  1470.     // but in selectUpdate(), minor updates trump major updates
  1471.     // if major trumps minor, and we said "never" to the major
  1472.     // we'd never see the minor update.
  1473.     //
  1474.     // note, the never decision should only apply to major updates
  1475.     // see bug #350636 for a scenario where this could potentially
  1476.     // be an issue
  1477.     //
  1478.     // fix for bug #359093
  1479.     // version might one day come back from AUS as an
  1480.     // arbitrary (and possibly non ascii) string, so we need to encode it
  1481.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH + encodeURIComponent(update.version);
  1482.     var never = getPref("getBoolPref", neverPrefName, false);
  1483.     if (never && update.type == "major")
  1484.       return;
  1485.  
  1486.     if (this._shouldPrompt(update))
  1487.       showPromptIfNoIncompatibilities(update);
  1488.     else {
  1489.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1490.       var status = this.downloadUpdate(update, true);
  1491.       if (status == STATE_NONE)
  1492.         cleanupActiveUpdate();
  1493.     }
  1494.   },
  1495.  
  1496.   /**
  1497.    * The Checker used for background update checks.
  1498.    */
  1499.   _backgroundChecker: null,
  1500.  
  1501.   /**
  1502.    * See nsIUpdateService.idl
  1503.    */
  1504.   get backgroundChecker() {
  1505.     if (!this._backgroundChecker)
  1506.       this._backgroundChecker = new Checker();
  1507.     return this._backgroundChecker;
  1508.   },
  1509.  
  1510.   /**
  1511.    * See nsIUpdateService.idl
  1512.    */
  1513.   get canUpdate() {
  1514.     try {
  1515.       var appDirFile = getUpdateFile([FILE_PERMS_TEST]);
  1516.       LOG("UpdateService", "canUpdate?  testing " + appDirFile.path);
  1517.       if (!appDirFile.exists()) {
  1518.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1519.         appDirFile.remove(false);
  1520.       }
  1521.       var updateDir = getUpdatesDir();
  1522.       var upDirFile = updateDir.clone();
  1523.       upDirFile.append(FILE_PERMS_TEST);
  1524.       LOG("UpdateService", "canUpdate?  testing " + upDirFile.path);
  1525.       if (!upDirFile.exists()) {
  1526.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1527.         upDirFile.remove(false);
  1528.       }
  1529. //@line 1647 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1530.     }
  1531.     catch (e) {
  1532.        LOG("UpdateService", "can't update, no privileges: " + e);
  1533.       // No write privileges to install directory
  1534.       return false;
  1535.     }
  1536.     // If the administrator has locked the app update functionality
  1537.     // OFF - this is not just a user setting, so disable the manual
  1538.     // UI too.
  1539.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1540.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED)) {
  1541.       LOG("UpdateService", "can't update, disabled by pref");
  1542.       return false;
  1543.     }
  1544.  
  1545.     // If we don't know the binary platform we're updating, we can't update.
  1546.     if (!gABI) {
  1547.       LOG("UpdateService", "can't update, unknown ABI");
  1548.       return false;
  1549.     }
  1550.  
  1551.     // If we don't know the OS version we're updating, we can't update.
  1552.     if (!gOSVersion) {
  1553.       LOG("UpdateService", "can't update, unknown OS version");
  1554.       return false;
  1555.     }
  1556.  
  1557.     LOG("UpdateService", "can update");
  1558.     return true;
  1559.   },
  1560.  
  1561.   /**
  1562.    * See nsIUpdateService.idl
  1563.    */
  1564.   addDownloadListener: function(listener) {
  1565.     if (!this._downloader) {
  1566.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1567.       return;
  1568.     }
  1569.     this._downloader.addDownloadListener(listener);
  1570.   },
  1571.  
  1572.   /**
  1573.    * See nsIUpdateService.idl
  1574.    */
  1575.   removeDownloadListener: function(listener) {
  1576.     if (!this._downloader) {
  1577.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1578.       return;
  1579.     }
  1580.     this._downloader.removeDownloadListener(listener);
  1581.   },
  1582.  
  1583.   /**
  1584.    * See nsIUpdateService.idl
  1585.    */
  1586.   downloadUpdate: function(update, background) {
  1587.     if (!update)
  1588.       throw Components.results.NS_ERROR_NULL_POINTER;
  1589.  
  1590.     var ai = Components.classes["@mozilla.org/xre/app-info;1"].
  1591.              getService(Components.interfaces.nsIXULAppInfo);
  1592.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  1593.              getService(Components.interfaces.nsIVersionComparator);
  1594.     // Don't download the update if the update's version is less than the
  1595.     // current application's version.
  1596.     if (update.extensionVersion &&
  1597.         vc.compare(update.extensionVersion, ai.version) < 0) {
  1598.       LOG("UpdateService", "downloadUpdate: removing update for previous " +
  1599.           "application version " + update.extensionVersion);
  1600.       cleanupActiveUpdate();
  1601.       return STATE_NONE;
  1602.     }
  1603.  
  1604.     if (this.isDownloading) {
  1605.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1606.           background == this._downloader.background) {
  1607.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1608.         return readStatusFile(getUpdatesDir());
  1609.       }
  1610.       this._downloader.cancel();
  1611.     }
  1612.     this._downloader = new Downloader(background);
  1613.     return this._downloader.downloadUpdate(update);
  1614.   },
  1615.  
  1616.   /**
  1617.    * See nsIUpdateService.idl
  1618.    */
  1619.   pauseDownload: function() {
  1620.     if (this.isDownloading)
  1621.       this._downloader.cancel();
  1622.   },
  1623.  
  1624.   /**
  1625.    * See nsIUpdateService.idl
  1626.    */
  1627.   get isDownloading() {
  1628.     return this._downloader && this._downloader.isBusy;
  1629.   },
  1630.  
  1631.   /**
  1632.    * See nsISupports.idl
  1633.    */
  1634.   QueryInterface: function(iid) {
  1635.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1636.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  1637.         !iid.equals(Components.interfaces.nsIObserver) &&
  1638.         !iid.equals(Components.interfaces.nsISupports))
  1639.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1640.     return this;
  1641.   }
  1642. };
  1643.  
  1644. /**
  1645.  * A service to manage active and past updates.
  1646.  * @constructor
  1647.  */
  1648. function UpdateManager() {
  1649.   // Ensure the Active Update file is loaded
  1650.   var updates = this._loadXMLFileIntoArray(getUpdateFile([FILE_UPDATE_ACTIVE]));
  1651.   if (updates.length > 0)
  1652.     this._activeUpdate = updates[0];
  1653. }
  1654. UpdateManager.prototype = {
  1655.   /**
  1656.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1657.    * objects.
  1658.    */
  1659.   _updates: null,
  1660.  
  1661.   /**
  1662.    * The current actively downloading/installing update, as a nsIUpdate object.
  1663.    */
  1664.   _activeUpdate: null,
  1665.  
  1666.   /**
  1667.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1668.    * @param   file
  1669.    *          A nsIFile for the updates.xml file
  1670.    * @returns The array of nsIUpdate items held in the file.
  1671.    */
  1672.   _loadXMLFileIntoArray: function(file) {
  1673.     if (!file.exists()) {
  1674.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1675.       return [];
  1676.     }
  1677.  
  1678.     var result = [];
  1679.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1680.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1681.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1682.     try {
  1683.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1684.                             .createInstance(Components.interfaces.nsIDOMParser);
  1685.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1686.  
  1687.       var updateCount = doc.documentElement.childNodes.length;
  1688.       for (var i = 0; i < updateCount; ++i) {
  1689.         var updateElement = doc.documentElement.childNodes.item(i);
  1690.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1691.             updateElement.localName != "update")
  1692.           continue;
  1693.  
  1694.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1695.         try {
  1696.           var update = new Update(updateElement);
  1697.         } catch (e) {
  1698.           LOG("UpdateManager", "_loadXMLFileIntoArray: invalid update");
  1699.           continue;
  1700.         }
  1701.         result.push(update);
  1702.       }
  1703.     }
  1704.     catch (e) {
  1705.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " +
  1706.           e);
  1707.     }
  1708.     fileStream.close();
  1709.     return result;
  1710.   },
  1711.  
  1712.   /**
  1713.    * Load the update manager, initializing state from state files.
  1714.    */
  1715.   _ensureUpdates: function() {
  1716.     if (!this._updates) {
  1717.       this._updates = this._loadXMLFileIntoArray(getUpdateFile(
  1718.                         [FILE_UPDATES_DB]));
  1719.  
  1720.       var activeUpdates = this._loadXMLFileIntoArray(getUpdateFile(
  1721.                             [FILE_UPDATE_ACTIVE]));
  1722.       if (activeUpdates.length > 0)
  1723.         this._activeUpdate = activeUpdates[0];
  1724.     }
  1725.   },
  1726.  
  1727.   /**
  1728.    * See nsIUpdateService.idl
  1729.    */
  1730.   getUpdateAt: function(index) {
  1731.     this._ensureUpdates();
  1732.     return this._updates[index];
  1733.   },
  1734.  
  1735.   /**
  1736.    * See nsIUpdateService.idl
  1737.    */
  1738.   get updateCount() {
  1739.     this._ensureUpdates();
  1740.     return this._updates.length;
  1741.   },
  1742.  
  1743.   /**
  1744.    * See nsIUpdateService.idl
  1745.    */
  1746.   get activeUpdate() {
  1747.     if (this._activeUpdate &&
  1748.         this._activeUpdate.channel != getUpdateChannel()) {
  1749.       // User switched channels, clear out any old active updates and remove
  1750.       // partial downloads
  1751.       this._activeUpdate = null;
  1752.  
  1753.       // Destroy the updates directory, since we're done with it.
  1754.       cleanUpUpdatesDir();
  1755.     }
  1756.     return this._activeUpdate;
  1757.   },
  1758.   set activeUpdate(activeUpdate) {
  1759.     this._addUpdate(activeUpdate);
  1760.     this._activeUpdate = activeUpdate;
  1761.     if (!activeUpdate) {
  1762.       // If |activeUpdate| is null, we have updated both lists - the active list
  1763.       // and the history list, so we want to write both files.
  1764.       this.saveUpdates();
  1765.     }
  1766.     else
  1767.       this._writeUpdatesToXMLFile([this._activeUpdate],
  1768.                                   getUpdateFile([FILE_UPDATE_ACTIVE]));
  1769.     return activeUpdate;
  1770.   },
  1771.  
  1772.   /**
  1773.    * Add an update to the Updates list. If the item already exists in the list,
  1774.    * replace the existing value with the new value.
  1775.    * @param   update
  1776.    *          The nsIUpdate object to add.
  1777.    */
  1778.   _addUpdate: function(update) {
  1779.     if (!update)
  1780.       return;
  1781.     this._ensureUpdates();
  1782.     if (this._updates) {
  1783.       for (var i = 0; i < this._updates.length; ++i) {
  1784.         if (this._updates[i] &&
  1785.             this._updates[i].version == update.version &&
  1786.             this._updates[i].buildID == update.buildID) {
  1787.           // Replace the existing entry with the new value, updating
  1788.           // all metadata.
  1789.           this._updates[i] = update;
  1790.           return;
  1791.         }
  1792.       }
  1793.     }
  1794.     // Otherwise add it to the front of the list.
  1795.     this._updates.unshift(update);
  1796.   },
  1797.  
  1798.   /**
  1799.    * Serializes an array of updates to an XML file
  1800.    * @param   updates
  1801.    *          An array of nsIUpdate objects
  1802.    * @param   file
  1803.    *          The nsIFile object to serialize to
  1804.    */
  1805.   _writeUpdatesToXMLFile: function(updates, file) {
  1806.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1807.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1808.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1809.     if (!file.exists())
  1810.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1811.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1812.  
  1813.     try {
  1814.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1815.                             .createInstance(Components.interfaces.nsIDOMParser);
  1816.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1817.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1818.  
  1819.       for (var i = 0; i < updates.length; ++i) {
  1820.         if (updates[i])
  1821.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1822.       }
  1823.  
  1824.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1825.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1826.       serializer.serializeToStream(doc.documentElement, fos, null);
  1827.     }
  1828.     catch (e) {
  1829.     }
  1830.  
  1831.     closeSafeOutputStream(fos);
  1832.   },
  1833.  
  1834.   /**
  1835.    * See nsIUpdateService.idl
  1836.    */
  1837.   saveUpdates: function() {
  1838.     this._writeUpdatesToXMLFile([this._activeUpdate],
  1839.                                 getUpdateFile([FILE_UPDATE_ACTIVE]));
  1840.     if (this._activeUpdate)
  1841.       this._addUpdate(this._activeUpdate);
  1842.  
  1843.     // Don't write updates that have a temporary state to the updates.xml file.
  1844.     if (this._updates) {
  1845.       var updates = this._updates.slice();
  1846.       for (var i = updates.length - 1; i >= 0; --i) {
  1847.         var state = updates[i].state;
  1848.         if (state == STATE_NONE || state == STATE_DOWNLOADING ||
  1849.             state == STATE_PENDING) {
  1850.           updates.splice(i, 1);
  1851.         }
  1852.       }
  1853.  
  1854.       this._writeUpdatesToXMLFile(updates.slice(0, 10),
  1855.                                   getUpdateFile([FILE_UPDATES_DB]));
  1856.     }
  1857.   },
  1858.  
  1859.   /**
  1860.    * See nsISupports.idl
  1861.    */
  1862.   QueryInterface: function(iid) {
  1863.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1864.         !iid.equals(Components.interfaces.nsISupports))
  1865.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1866.     return this;
  1867.   }
  1868. };
  1869.  
  1870.  
  1871. /**
  1872.  * Checker
  1873.  * Checks for new Updates
  1874.  * @constructor
  1875.  */
  1876. function Checker() {
  1877. }
  1878. Checker.prototype = {
  1879.   /**
  1880.    * The XMLHttpRequest object that performs the connection.
  1881.    */
  1882.   _request  : null,
  1883.  
  1884.   /**
  1885.    * The nsIUpdateCheckListener callback
  1886.    */
  1887.   _callback : null,
  1888.  
  1889.   /**
  1890.    * The URL of the update service XML file to connect to that contains details
  1891.    * about available updates.
  1892.    */
  1893.   getUpdateURL: function(force) {
  1894.     this._forced = force;
  1895.  
  1896.     var defaults =
  1897.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1898.         getDefaultBranch(null);
  1899.  
  1900.     // Use the override URL if specified.
  1901.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1902.  
  1903.     // Otherwise, construct the update URL from component parts.
  1904.     if (!url) {
  1905.       try {
  1906.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1907.       } catch (e) {
  1908.       }
  1909.     }
  1910.  
  1911.     if (!url || url == "") {
  1912.       LOG("Checker", "Update URL not defined");
  1913.       return null;
  1914.     }
  1915.  
  1916.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1917.     url = url.replace(/%VERSION%/g, gApp.version);
  1918.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1919.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  1920.     url = url.replace(/%OS_VERSION%/g, gOSVersion);
  1921.     url = url.replace(/%LOCALE%/g, getLocale());
  1922.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1923.     url = url.replace(/%PLATFORM_VERSION%/g, gApp.platformVersion);
  1924.     url = url.replace(/%DISTRIBUTION%/g,
  1925.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION));
  1926.     url = url.replace(/%DISTRIBUTION_VERSION%/g,
  1927.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION_VERSION));
  1928.     url = url.replace(/\+/g, "%2B");
  1929.  
  1930.     if (force)
  1931.     url += "?force=1"
  1932.  
  1933.     LOG("Checker", "update url: " + url);
  1934.     return url;
  1935.   },
  1936.  
  1937.   /**
  1938.    * See nsIUpdateService.idl
  1939.    */
  1940.   checkForUpdates: function(listener, force) {
  1941.     if (!listener)
  1942.       throw Components.results.NS_ERROR_NULL_POINTER;
  1943.  
  1944.     if (!this.getUpdateURL(force) || (!this.enabled && !force))
  1945.       return;
  1946.  
  1947.     this._request =
  1948.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1949.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1950.     this._request.open("GET", this.getUpdateURL(force), true);
  1951.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1952.     this._request.overrideMimeType("text/xml");
  1953.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1954.  
  1955.     var self = this;
  1956.     this._request.onerror     = function(event) { self.onError(event);    };
  1957.     this._request.onload      = function(event) { self.onLoad(event);     };
  1958.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1959.  
  1960.     LOG("Checker", "checkForUpdates: sending request to " + this.getUpdateURL(force));
  1961.     this._request.send(null);
  1962.  
  1963.     this._callback = listener;
  1964.   },
  1965.  
  1966.   /**
  1967.    * When progress associated with the XMLHttpRequest is received.
  1968.    * @param   event
  1969.    *          The nsIDOMLSProgressEvent for the load.
  1970.    */
  1971.   onProgress: function(event) {
  1972.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1973.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1974.   },
  1975.  
  1976.   /**
  1977.    * Returns an array of nsIUpdate objects discovered by the update check.
  1978.    */
  1979.   get _updates() {
  1980.     var updatesElement = this._request.responseXML.documentElement;
  1981.     if (!updatesElement) {
  1982.       LOG("Checker", "get_updates: empty updates document?!");
  1983.       return [];
  1984.     }
  1985.  
  1986.     if (updatesElement.nodeName != "updates") {
  1987.       LOG("Checker", "get_updates: unexpected node name!");
  1988.       throw "";
  1989.     }
  1990.  
  1991.     var updates = [];
  1992.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  1993.       var updateElement = updatesElement.childNodes.item(i);
  1994.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1995.           updateElement.localName != "update")
  1996.         continue;
  1997.  
  1998.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1999.       try {
  2000.         var update = new Update(updateElement);
  2001.       } catch (e) {
  2002.         LOG("Checker", "Invalid <update/>, ignoring...");
  2003.         continue;
  2004.       }
  2005.       update.serviceURL = this.getUpdateURL(this._forced);
  2006.       update.channel = getUpdateChannel();
  2007.       updates.push(update);
  2008.     }
  2009.  
  2010.     return updates;
  2011.   },
  2012.  
  2013.   /**
  2014.    * The XMLHttpRequest succeeded and the document was loaded.
  2015.    * @param   event
  2016.    *          The nsIDOMLSEvent for the load
  2017.    */
  2018.   onLoad: function(event) {
  2019.     LOG("Checker", "onLoad: request completed downloading document");
  2020.  
  2021.     try {
  2022.       checkCert(this._request.channel);
  2023.  
  2024.       // Analyze the resulting DOM and determine the set of updates to install
  2025.       var updates = this._updates;
  2026.  
  2027.       LOG("Checker", "Updates available: " + updates.length);
  2028.  
  2029.       // ... and tell the Update Service about what we discovered.
  2030.       this._callback.onCheckComplete(event.target, updates, updates.length);
  2031.     }
  2032.     catch (e) {
  2033.       LOG("Checker", "There was a problem with the update service URL specified, " +
  2034.           "either the XML file was malformed or it does not exist at the location " +
  2035.           "specified. Exception: " + e);
  2036.       var update = new Update(null);
  2037.       update.statusText = getStatusTextFromCode(404, 404);
  2038.       this._callback.onError(event.target, update);
  2039.     }
  2040.  
  2041.     this._request = null;
  2042.   },
  2043.  
  2044.   /**
  2045.    * There was an error of some kind during the XMLHttpRequest
  2046.    * @param   event
  2047.    *          The nsIDOMLSEvent for the load
  2048.    */
  2049.   onError: function(event) {
  2050.     LOG("Checker", "onError: error during load");
  2051.  
  2052.     var request = event.target;
  2053.     try {
  2054.       var status = request.status;
  2055.     }
  2056.     catch (e) {
  2057.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  2058.       status = req.status;
  2059.     }
  2060.  
  2061.     // If we can't find an error string specific to this status code,
  2062.     // just use the 200 message from above, which means everything
  2063.     // "looks" fine but there was probably an XML error or a bogus file.
  2064.     var update = new Update(null);
  2065.     update.statusText = getStatusTextFromCode(status, 200);
  2066.     this._callback.onError(request, update);
  2067.  
  2068.     this._request = null;
  2069.   },
  2070.  
  2071.   /**
  2072.    * Whether or not we are allowed to do update checking.
  2073.    */
  2074.   _enabled: true,
  2075.  
  2076.   /**
  2077.    * See nsIUpdateService.idl
  2078.    */
  2079.   get enabled() {
  2080.     var aus =
  2081.         Components.classes["@mozilla.org/updates/update-service;1"].
  2082.         getService(Components.interfaces.nsIApplicationUpdateService);
  2083.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) &&
  2084.                   aus.canUpdate && this._enabled;
  2085.     return enabled;
  2086.   },
  2087.  
  2088.   /**
  2089.    * See nsIUpdateService.idl
  2090.    */
  2091.   stopChecking: function(duration) {
  2092.     // Always stop the current check
  2093.     if (this._request)
  2094.       this._request.abort();
  2095.  
  2096.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  2097.     switch (duration) {
  2098.     case nsIUpdateChecker.CURRENT_SESSION:
  2099.       this._enabled = false;
  2100.       break;
  2101.     case nsIUpdateChecker.ANY_CHECKS:
  2102.       this._enabled = false;
  2103.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  2104.       break;
  2105.     }
  2106.   },
  2107.  
  2108.   /**
  2109.    * See nsISupports.idl
  2110.    */
  2111.   QueryInterface: function(iid) {
  2112.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  2113.         !iid.equals(Components.interfaces.nsISupports))
  2114.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2115.     return this;
  2116.   }
  2117. };
  2118.  
  2119. /**
  2120.  * Manages the download of updates
  2121.  * @param   background
  2122.  *          Whether or not this downloader is operating in background
  2123.  *          update mode.
  2124.  * @constructor
  2125.  */
  2126. function Downloader(background) {
  2127.   this.background = background;
  2128. }
  2129. Downloader.prototype = {
  2130.   /**
  2131.    * The nsIUpdatePatch that we are downloading
  2132.    */
  2133.   _patch: null,
  2134.  
  2135.   /**
  2136.    * The nsIUpdate that we are downloading
  2137.    */
  2138.   _update: null,
  2139.  
  2140.   /**
  2141.    * The nsIIncrementalDownload object handling the download
  2142.    */
  2143.   _request: null,
  2144.  
  2145.   /**
  2146.    * Whether or not the update being downloaded is a complete replacement of
  2147.    * the user's existing installation or a patch representing the difference
  2148.    * between the new version and the previous version.
  2149.    */
  2150.   isCompleteUpdate: null,
  2151.  
  2152.   /**
  2153.    * Cancels the active download.
  2154.    */
  2155.   cancel: function() {
  2156.     if (this._request &&
  2157.         this._request instanceof Components.interfaces.nsIRequest) {
  2158.       const NS_BINDING_ABORTED = 0x804b0002;
  2159.       this._request.cancel(NS_BINDING_ABORTED);
  2160.     }
  2161.   },
  2162.  
  2163.   /**
  2164.    * Whether or not a patch has been downloaded and staged for installation.
  2165.    */
  2166.   get patchIsStaged() {
  2167.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  2168.   },
  2169.  
  2170.   /**
  2171.    * Verify the downloaded file.  We assume that the download is complete at
  2172.    * this point.
  2173.    */
  2174.   _verifyDownload: function() {
  2175.     if (!this._request)
  2176.       return false;
  2177.  
  2178.     var destination = this._request.destination;
  2179.  
  2180.     // Ensure that the file size matches the expected file size.
  2181.     if (destination.fileSize != this._patch.size)
  2182.       return false;
  2183.  
  2184.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  2185.         createInstance(nsIFileInputStream);
  2186.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2187.  
  2188.     try {
  2189.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  2190.           createInstance(nsICryptoHash);
  2191.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2192.       if (hashFunction == undefined)
  2193.         throw Components.results.NS_ERROR_UNEXPECTED;
  2194.       hash.init(hashFunction);
  2195.       hash.updateFromStream(fileStream, -1);
  2196.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2197.       // encoded binary (such as what is typically output by programs like
  2198.       // sha1sum).  In the future, this may change to base64 depending on how
  2199.       // we choose to compute these hashes.
  2200.       digest = binaryToHex(hash.finish(false));
  2201.     } catch (e) {
  2202.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  2203.       digest = "";
  2204.     }
  2205.  
  2206.     fileStream.close();
  2207.  
  2208.     return digest == this._patch.hashValue.toLowerCase();
  2209.   },
  2210.  
  2211.   /**
  2212.    * Select the patch to use given the current state of updateDir and the given
  2213.    * set of update patches.
  2214.    * @param   update
  2215.    *          A nsIUpdate object to select a patch from
  2216.    * @param   updateDir
  2217.    *          A nsIFile representing the update directory
  2218.    * @returns A nsIUpdatePatch object to download
  2219.    */
  2220.   _selectPatch: function(update, updateDir) {
  2221.     // Given an update to download, we will always try to download the patch
  2222.     // for a partial update over the patch for a full update.
  2223.  
  2224.     /**
  2225.      * Return the first UpdatePatch with the given type.
  2226.      * @param   type
  2227.      *          The type of the patch ("complete" or "partial")
  2228.      * @returns A nsIUpdatePatch object matching the type specified
  2229.      */
  2230.     function getPatchOfType(type) {
  2231.       for (var i = 0; i < update.patchCount; ++i) {
  2232.         var patch = update.getPatchAt(i);
  2233.         if (patch && patch.type == type)
  2234.           return patch;
  2235.       }
  2236.       return null;
  2237.     }
  2238.  
  2239.     // Look to see if any of the patches in the Update object has been
  2240.     // pre-selected for download, otherwise we must figure out which one
  2241.     // to select ourselves.
  2242.     var selectedPatch = update.selectedPatch;
  2243.  
  2244.     var state = readStatusFile(updateDir);
  2245.  
  2246.     // If this is a patch that we know about, then select it.  If it is a patch
  2247.     // that we do not know about, then remove it and use our default logic.
  2248.     var useComplete = false;
  2249.     if (selectedPatch) {
  2250.       LOG("Downloader", "found existing patch [state="+state+"]");
  2251.       switch (state) {
  2252.       case STATE_DOWNLOADING:
  2253.         LOG("Downloader", "resuming download");
  2254.         return selectedPatch;
  2255.       case STATE_PENDING:
  2256.         LOG("Downloader", "already downloaded and staged");
  2257.         return null;
  2258.       default:
  2259.         // Something went wrong when we tried to apply the previous patch.
  2260.         // Try the complete patch next time.
  2261.         if (update && selectedPatch.type == "partial") {
  2262.           useComplete = true;
  2263.         } else {
  2264.           // This is a pretty fatal error.  Just bail.
  2265.           LOG("Downloader", "failed to apply complete patch!");
  2266.           writeStatusFile(updateDir, STATE_NONE);
  2267.           writeVersionFile(getUpdatesDir(), null);
  2268.           return null;
  2269.         }
  2270.       }
  2271.  
  2272.       selectedPatch = null;
  2273.     }
  2274.  
  2275.     // If we were not able to discover an update from a previous download, we
  2276.     // select the best patch from the given set.
  2277.     var partialPatch = getPatchOfType("partial");
  2278.     if (!useComplete)
  2279.       selectedPatch = partialPatch;
  2280.     if (!selectedPatch) {
  2281.       if (partialPatch)
  2282.         partialPatch.selected = false;
  2283.       selectedPatch = getPatchOfType("complete");
  2284.     }
  2285.  
  2286.     // Restore the updateDir since we may have deleted it.
  2287.     updateDir = getUpdatesDir();
  2288.  
  2289.     // if update only contains a partial patch, selectedPatch == null here if
  2290.     // the partial patch has been attempted and fails and we're trying to get a
  2291.     // complete patch
  2292.     if (selectedPatch)
  2293.       selectedPatch.selected = true;
  2294.  
  2295.     update.isCompleteUpdate = useComplete;
  2296.  
  2297.     // Reset the Active Update object on the Update Manager and flush the
  2298.     // Active Update DB.
  2299.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2300.                        .getService(Components.interfaces.nsIUpdateManager);
  2301.     um.activeUpdate = update;
  2302.  
  2303.     return selectedPatch;
  2304.   },
  2305.  
  2306.   /**
  2307.    * Whether or not we are currently downloading something.
  2308.    */
  2309.   get isBusy() {
  2310.     return this._request != null;
  2311.   },
  2312.  
  2313.   /**
  2314.    * Download and stage the given update.
  2315.    * @param   update
  2316.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2317.    */
  2318.   downloadUpdate: function(update) {
  2319.     if (!update)
  2320.       throw Components.results.NS_ERROR_NULL_POINTER;
  2321.  
  2322.     var updateDir = getUpdatesDir();
  2323.  
  2324.     this._update = update;
  2325.  
  2326.     // This function may return null, which indicates that there are no patches
  2327.     // to download.
  2328.     this._patch = this._selectPatch(update, updateDir);
  2329.     if (!this._patch) {
  2330.       LOG("Downloader", "no patch to download");
  2331.       return readStatusFile(updateDir);
  2332.     }
  2333.     this.isCompleteUpdate = this._patch.type == "complete";
  2334.  
  2335.     var patchFile = updateDir.clone();
  2336.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2337.  
  2338.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2339.         getService(Components.interfaces.nsIIOService);
  2340.     var uri = ios.newURI(this._patch.URL, null, null);
  2341.  
  2342.     this._request =
  2343.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2344.         createInstance(nsIIncrementalDownload);
  2345.  
  2346.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " +
  2347.         patchFile.path);
  2348.  
  2349.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2350.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2351.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2352.     this._request.start(this, null);
  2353.  
  2354.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2355.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2356.     this._patch.state = STATE_DOWNLOADING;
  2357.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2358.                        .getService(Components.interfaces.nsIUpdateManager);
  2359.     um.saveUpdates();
  2360.     return STATE_DOWNLOADING;
  2361.   },
  2362.  
  2363.   /**
  2364.    * An array of download listeners to notify when we receive
  2365.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2366.    */
  2367.   _listeners: [],
  2368.  
  2369.   /**
  2370.    * Adds a listener to the download process
  2371.    * @param   listener
  2372.    *          A download listener, implementing nsIRequestObserver and
  2373.    *          nsIProgressEventSink
  2374.    */
  2375.   addDownloadListener: function(listener) {
  2376.     for (var i = 0; i < this._listeners.length; ++i) {
  2377.       if (this._listeners[i] == listener)
  2378.         return;
  2379.     }
  2380.     this._listeners.push(listener);
  2381.   },
  2382.  
  2383.   /**
  2384.    * Removes a download listener
  2385.    * @param   listener
  2386.    *          The listener to remove.
  2387.    */
  2388.   removeDownloadListener: function(listener) {
  2389.     for (var i = 0; i < this._listeners.length; ++i) {
  2390.       if (this._listeners[i] == listener) {
  2391.         this._listeners.splice(i, 1);
  2392.         return;
  2393.       }
  2394.     }
  2395.   },
  2396.  
  2397.   /**
  2398.    * When the async request begins
  2399.    * @param   request
  2400.    *          The nsIRequest object for the transfer
  2401.    * @param   context
  2402.    *          Additional data
  2403.    */
  2404.   onStartRequest: function(request, context) {
  2405.     request.QueryInterface(nsIIncrementalDownload);
  2406.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2407.  
  2408.     var listenerCount = this._listeners.length;
  2409.     for (var i = 0; i < listenerCount; ++i)
  2410.       this._listeners[i].onStartRequest(request, context);
  2411.   },
  2412.  
  2413.   /**
  2414.    * When new data has been downloaded
  2415.    * @param   request
  2416.    *          The nsIRequest object for the transfer
  2417.    * @param   context
  2418.    *          Additional data
  2419.    * @param   progress
  2420.    *          The current number of bytes transferred
  2421.    * @param   maxProgress
  2422.    *          The total number of bytes that must be transferred
  2423.    */
  2424.   onProgress: function(request, context, progress, maxProgress) {
  2425.     request.QueryInterface(nsIIncrementalDownload);
  2426.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2427.  
  2428.     var listenerCount = this._listeners.length;
  2429.     for (var i = 0; i < listenerCount; ++i) {
  2430.       var listener = this._listeners[i];
  2431.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2432.         listener.onProgress(request, context, progress, maxProgress);
  2433.     }
  2434.   },
  2435.  
  2436.   /**
  2437.    * When we have new status text
  2438.    * @param   request
  2439.    *          The nsIRequest object for the transfer
  2440.    * @param   context
  2441.    *          Additional data
  2442.    * @param   status
  2443.    *          A status code
  2444.    * @param   statusText
  2445.    *          Human readable version of |status|
  2446.    */
  2447.   onStatus: function(request, context, status, statusText) {
  2448.     request.QueryInterface(nsIIncrementalDownload);
  2449.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2450.     var listenerCount = this._listeners.length;
  2451.     for (var i = 0; i < listenerCount; ++i) {
  2452.       var listener = this._listeners[i];
  2453.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2454.         listener.onStatus(request, context, status, statusText);
  2455.     }
  2456.   },
  2457.  
  2458.   /**
  2459.    * When data transfer ceases
  2460.    * @param   request
  2461.    *          The nsIRequest object for the transfer
  2462.    * @param   context
  2463.    *          Additional data
  2464.    * @param   status
  2465.    *          Status code containing the reason for the cessation.
  2466.    */
  2467.   onStopRequest: function(request, context, status) {
  2468.     request.QueryInterface(nsIIncrementalDownload);
  2469.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2470.  
  2471.     var state = this._patch.state;
  2472.     var shouldShowPrompt = false;
  2473.     var deleteActiveUpdate = false;
  2474.     const NS_BINDING_ABORTED = 0x804b0002;
  2475.     const NS_ERROR_ABORT = 0x80004004;
  2476.     if (Components.isSuccessCode(status)) {
  2477.       var sbs =
  2478.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  2479.           getService(Components.interfaces.nsIStringBundleService);
  2480.       var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2481.       if (this._verifyDownload()) {
  2482.         state = STATE_PENDING;
  2483.  
  2484.         // We only need to explicitly show the prompt if this is a backround
  2485.         // download, since otherwise some kind of UI is already visible and
  2486.         // that UI will notify.
  2487.         if (this.background)
  2488.           shouldShowPrompt = true;
  2489.  
  2490.         // Tell the updater.exe we're ready to apply.
  2491.         writeStatusFile(getUpdatesDir(), state);
  2492.         writeVersionFile(getUpdatesDir(), this._update.extensionVersion);
  2493.         this._update.installDate = (new Date()).getTime();
  2494.         this._update.statusText = updateStrings.
  2495.           GetStringFromName("installPending");
  2496.       } else {
  2497.         LOG("Downloader", "onStopRequest: download verification failed");
  2498.         state = STATE_DOWNLOAD_FAILED;
  2499.  
  2500.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2501.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2502.         this._update.statusText = updateStrings.
  2503.           formatStringFromName("verificationError", [brandShortName], 1);
  2504.  
  2505.         // TODO: use more informative error code here
  2506.         status = Components.results.NS_ERROR_UNEXPECTED;
  2507.  
  2508.         var message = getStatusTextFromCode("verification_failed",
  2509.           "verification_failed");
  2510.         this._update.statusText = message;
  2511.  
  2512.         if (this._update.isCompleteUpdate)
  2513.           deleteActiveUpdate = true;
  2514.  
  2515.         // Destroy the updates directory, since we're done with it.
  2516.         cleanUpUpdatesDir();
  2517.       }
  2518.     }
  2519.     else if (status != NS_BINDING_ABORTED &&
  2520.              status != NS_ERROR_ABORT) {
  2521.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2522.       // Some sort of other failure, log this in the |statusText| property
  2523.       state = STATE_DOWNLOAD_FAILED;
  2524.  
  2525.       // XXXben - if |request| (The Incremental Download) provided a means
  2526.       // for accessing the http channel we could do more here.
  2527.  
  2528.       const NS_BINDING_FAILED = 2152398849;
  2529.       this._update.statusText = getStatusTextFromCode(status,
  2530.         NS_BINDING_FAILED);
  2531.  
  2532.       // Destroy the updates directory, since we're done with it.
  2533.       cleanUpUpdatesDir();
  2534.  
  2535.       deleteActiveUpdate = true;
  2536.     }
  2537.     LOG("Downloader", "Setting state to: " + state);
  2538.     this._patch.state = state;
  2539.     var um =
  2540.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2541.         getService(Components.interfaces.nsIUpdateManager);
  2542.     if (deleteActiveUpdate) {
  2543.       this._update.installDate = (new Date()).getTime();
  2544.       um.activeUpdate = null;
  2545.     }
  2546.     else {
  2547.       if (um.activeUpdate)
  2548.         um.activeUpdate.state = state;
  2549.     }
  2550.     um.saveUpdates();
  2551.  
  2552.     var listenerCount = this._listeners.length;
  2553.     for (var i = 0; i < listenerCount; ++i)
  2554.       this._listeners[i].onStopRequest(request, context, status);
  2555.  
  2556.     this._request = null;
  2557.  
  2558.     if (state == STATE_DOWNLOAD_FAILED) {
  2559.       if (!this._update.isCompleteUpdate) {
  2560.         var allFailed = true;
  2561.  
  2562.         // If we were downloading a patch and the patch verification phase
  2563.         // failed, log this and then commence downloading the complete update.
  2564.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2565.         this._update.isCompleteUpdate = true;
  2566.         var status = this.downloadUpdate(this._update);
  2567.  
  2568.         if (status == STATE_NONE) {
  2569.           cleanupActiveUpdate();
  2570.         } else {
  2571.           allFailed = false;
  2572.         }
  2573.         // This will reset the |.state| property on this._update if a new
  2574.         // download initiates.
  2575.       }
  2576.  
  2577.       // if we still fail after trying a complete download, give up completely
  2578.       if (allFailed) {
  2579.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2580.         // ...
  2581.  
  2582.         // If this was ever a foreground download, and now there is no UI active
  2583.         // (e.g. because the user closed the download window) and there was an
  2584.         // error, we must notify now. Otherwise we can keep the failure to
  2585.         // ourselves since the user won't be expecting it.
  2586.         try {
  2587.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2588.           var fgdl = this._update.getProperty("foregroundDownload");
  2589.         }
  2590.         catch (e) {
  2591.         }
  2592.  
  2593.         if (fgdl == "true") {
  2594.           var prompter =
  2595.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2596.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2597.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2598.           this._update.setProperty("downloadFailed", "true");
  2599.           prompter.showUpdateError(this._update);
  2600.         }
  2601.       }
  2602.  
  2603.       // the complete download succeeded or total failure was handled, so exit
  2604.       return;
  2605.     }
  2606.  
  2607.     // Do this after *everything* else, since it will likely cause the app
  2608.     // to shut down.
  2609.     if (shouldShowPrompt) {
  2610.       // Notify the user that an update has been downloaded and is ready for
  2611.       // installation (i.e. that they should restart the application). We do
  2612.       // not notify on failed update attempts.
  2613.       var prompter =
  2614.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2615.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2616.       prompter.showUpdateDownloaded(this._update, true);
  2617.     }
  2618.   },
  2619.  
  2620.   /**
  2621.    * See nsIInterfaceRequestor.idl
  2622.    */
  2623.   getInterface: function(iid) {
  2624.     // The network request may require proxy authentication, so provide the
  2625.     // default nsIAuthPrompt if requested.
  2626.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2627.       var prompt =
  2628.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2629.           createInstance();
  2630.       return prompt.QueryInterface(iid);
  2631.     }
  2632.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2633.   },
  2634.  
  2635.   /**
  2636.    * See nsISupports.idl
  2637.    */
  2638.   QueryInterface: function(iid) {
  2639.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2640.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2641.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2642.         !iid.equals(Components.interfaces.nsISupports))
  2643.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2644.     return this;
  2645.   }
  2646. };
  2647.  
  2648. /**
  2649.  * A manager for update check timers. Manages timers that fire over long
  2650.  * periods of time (e.g. days, weeks).
  2651.  * @constructor
  2652.  */
  2653. function TimerManager() {
  2654.   getObserverService().addObserver(this, "xpcom-shutdown", false);
  2655.  
  2656.   const nsITimer = Components.interfaces.nsITimer;
  2657.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2658.                           .createInstance(nsITimer);
  2659.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2660.   this._timer.initWithCallback(this, timerInterval,
  2661.                                nsITimer.TYPE_REPEATING_SLACK);
  2662. }
  2663. TimerManager.prototype = {
  2664.   /**
  2665.    * See nsIObserver.idl
  2666.    */
  2667.   observe: function(subject, topic, data) {
  2668.     if (topic == "xpcom-shutdown") {
  2669.      getObserverService().removeObserver(this, "xpcom-shutdown");
  2670.  
  2671.       // Release everything we hold onto.
  2672.       for (var timerID in this._timers)
  2673.         delete this._timers[timerID];
  2674.       this._timer = null;
  2675.       this._timers = null;
  2676.     }
  2677.   },
  2678.  
  2679.   /**
  2680.    * The Checker Timer
  2681.    */
  2682.   _timer: null,
  2683.  
  2684.   /**
  2685.    * The set of registered timers.
  2686.    */
  2687.   _timers: { },
  2688.  
  2689.   /**
  2690.    * Called when the checking timer fires.
  2691.    * @param   timer
  2692.    *          The checking timer that fired.
  2693.    */
  2694.   notify: function(timer) {
  2695.     for (var timerID in this._timers) {
  2696.       var timerData = this._timers[timerID];
  2697.       var lastUpdateTime = timerData.lastUpdateTime;
  2698.       var now = Math.round(Date.now() / 1000);
  2699.  
  2700.       // Fudge the lastUpdateTime by some random increment of the update
  2701.       // check interval (e.g. some random slice of 10 minutes) so that when
  2702.       // the time comes to check, we offset each client request by a random
  2703.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2704.       // whereas app.update.lastUpdateTime is in seconds
  2705.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2706.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2707.  
  2708.       if ((now - lastUpdateTime) > timerData.interval &&
  2709.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2710.         timerData.callback.notify(timer);
  2711.         timerData.lastUpdateTime = now;
  2712.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2713.         gPref.setIntPref(preference, now);
  2714.       }
  2715.     }
  2716.   },
  2717.  
  2718.   /**
  2719.    * See nsIUpdateService.idl
  2720.    */
  2721.   registerTimer: function(id, callback, interval) {
  2722.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2723.     var now = Math.round(Date.now() / 1000);
  2724.     var lastUpdateTime = null;
  2725.     if (gPref.prefHasUserValue(preference)) {
  2726.       lastUpdateTime = gPref.getIntPref(preference);
  2727.     } else {
  2728.       gPref.setIntPref(preference, now);
  2729.       lastUpdateTime = now;
  2730.     }
  2731.     this._timers[id] = { callback       : callback,
  2732.                          interval       : interval,
  2733.                          lastUpdateTime : lastUpdateTime };
  2734.   },
  2735.  
  2736.   /**
  2737.    * See nsISupports.idl
  2738.    */
  2739.   QueryInterface: function(iid) {
  2740.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2741.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2742.         !iid.equals(Components.interfaces.nsIObserver) &&
  2743.         !iid.equals(Components.interfaces.nsISupports))
  2744.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2745.     return this;
  2746.   }
  2747. };
  2748.  
  2749. //@line 2867 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2750. /**
  2751.  * UpdatePrompt
  2752.  * An object which can prompt the user with information about updates, request
  2753.  * action, etc. Embedding clients can override this component with one that
  2754.  * invokes a native front end.
  2755.  * @constructor
  2756.  */
  2757. function UpdatePrompt() {
  2758. }
  2759. UpdatePrompt.prototype = {
  2760.   /**
  2761.    * See nsIUpdateService.idl
  2762.    */
  2763.   checkForUpdates: function() {
  2764.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2765.                  null, null);
  2766.   },
  2767.  
  2768.   /**
  2769.    * See nsIUpdateService.idl
  2770.    */
  2771.   showUpdateAvailable: function(update) {
  2772.     if (!this._enabled)
  2773.       return;
  2774.     var bundle = this._updateBundle;
  2775.     var stringsPrefix = "updateAvailable_" + update.type + ".";
  2776.     var title = bundle.formatStringFromName(stringsPrefix + "title", [update.name], 1);
  2777.     var text = bundle.GetStringFromName(stringsPrefix + "text");
  2778.     var imageUrl = "";
  2779.     this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2780.                            "Update:Wizard", "updatesavailable", update,
  2781.                            title, text, imageUrl);
  2782.   },
  2783.  
  2784.   /**
  2785.    * See nsIUpdateService.idl
  2786.    */
  2787.   showUpdateDownloaded: function(update, background) {
  2788.     if (background) {
  2789.       if (!this._enabled)
  2790.         return;
  2791.       var bundle = this._updateBundle;
  2792.       var stringsPrefix = "updateDownloaded_" + update.type + ".";
  2793.       var title = bundle.formatStringFromName(stringsPrefix + "title", [update.name], 1);
  2794.       var text = bundle.GetStringFromName(stringsPrefix + "text");
  2795.       var imageUrl = "";
  2796.       this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2797.                               "Update:Wizard", "finishedBackground", update,
  2798.                               title, text, imageUrl);
  2799.     } else {
  2800.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2801.                    "Update:Wizard", "finishedBackground", update);
  2802.     }
  2803.   },
  2804.  
  2805.   /**
  2806.    * See nsIUpdateService.idl
  2807.    */
  2808.   showUpdateInstalled: function(update) {
  2809.     var showUpdateInstalledUI = getPref("getBoolPref",
  2810.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2811.     if (this._enabled && showUpdateInstalledUI) {
  2812.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2813.                    "installed", update);
  2814.     }
  2815.   },
  2816.  
  2817.   /**
  2818.    * See nsIUpdateService.idl
  2819.    */
  2820.   showUpdateError: function(update) {
  2821.     if (this._enabled) {
  2822.       // In some cases, we want to just show a simple alert dialog:
  2823.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2824.         var updateBundle = this._updateBundle;
  2825.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2826.         var text = updateBundle.formatStringFromName("updaterIOErrorMsg",
  2827.                                                      [gApp.name, gApp.name], 2);
  2828.         var ww =
  2829.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2830.             getService(Components.interfaces.nsIWindowWatcher);
  2831.         ww.getNewPrompter(null).alert(title, text);
  2832.       } else {
  2833.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2834.                      "errors", update);
  2835.       }
  2836.     }
  2837.   },
  2838.  
  2839.   /**
  2840.    * See nsIUpdateService.idl
  2841.    */
  2842.   showUpdateHistory: function(parent) {
  2843.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History",
  2844.                  null, null);
  2845.   },
  2846.  
  2847.   /**
  2848.    * Whether or not we are enabled (i.e. not in Silent mode)
  2849.    */
  2850.   get _enabled() {
  2851.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2852.   },
  2853.  
  2854.   get _updateBundle() {
  2855.     return Components.classes["@mozilla.org/intl/stringbundle;1"]
  2856.                      .getService(Components.interfaces.nsIStringBundleService)
  2857.                      .createBundle(URI_UPDATES_PROPERTIES);
  2858.   },
  2859.  
  2860.   /**
  2861.    * Initiate a less obtrusive UI, starting with a non-modal notification alert
  2862.    * @param   parent
  2863.    *          A parent window, can be null
  2864.    * @param   uri
  2865.    *          The URI string of the dialog to show
  2866.    * @param   name
  2867.    *          The Window Name of the dialog to show, in case it is already open
  2868.    *          and can merely be focused
  2869.    * @param   page
  2870.    *          The page of the wizard to be displayed, if one is already open.
  2871.    * @param   update
  2872.    *          An update to pass to the UI in the window arguments.
  2873.    *          Can be null
  2874.    * @param   title
  2875.    *          The title for the notification alert.
  2876.    * @param   text
  2877.    *          The contents of the notification alert.
  2878.    * @param   imageUrl
  2879.    *          A URL identifying the image to put in the notification alert.
  2880.    */
  2881.   _showUnobtrusiveUI: function(parent, uri, features, name, page, update,
  2882.                                title, text, imageUrl) {
  2883.     var observer = {
  2884.       updatePrompt: this,
  2885.       service: null,
  2886.       timer: null,
  2887.       notify: function () {
  2888.         // the user hasn't restarted yet => prompt when idle
  2889.         this.service.removeObserver(this, "quit-application");
  2890.         this.updatePrompt._showUIWhenIdle(parent, uri, features, name, page, update);
  2891.       },
  2892.       observe: function (aSubject, aTopic, aData) {
  2893.         switch (aTopic) {
  2894.           case "alertclickcallback":
  2895.             this.updatePrompt._showUI(parent, uri, features, name, page, update);
  2896.             // fall thru
  2897.           case "quit-application":
  2898.             this.timer.cancel();
  2899.             this.service.removeObserver(this, "quit-application");
  2900.             break;
  2901.         }
  2902.       }
  2903.     };
  2904.  
  2905.     try {
  2906.       var notifier = Components.classes["@mozilla.org/alerts-service;1"]
  2907.                                .getService(Components.interfaces.nsIAlertsService);
  2908.       notifier.showAlertNotification(imageUrl, title, text, true, "", observer);
  2909.     }
  2910.     catch (e) {
  2911.       // Failed to retrieve alerts service, platform unsupported
  2912.       this._showUIWhenIdle(parent, uri, features, name, page, update);
  2913.       return;
  2914.     }
  2915.  
  2916.     observer.service =
  2917.       Components.classes["@mozilla.org/observer-service;1"]
  2918.                 .getService(Components.interfaces.nsIObserverService);
  2919.     observer.service.addObserver(observer, "quit-application", false);
  2920.  
  2921.     // Give the user x seconds to react before showing the big UI
  2922.     var promptWaitTime = getPref("getIntPref", PREF_APP_UPDATE_PROMPTWAITTIME, 43200);
  2923.     observer.timer =
  2924.       Components.classes["@mozilla.org/timer;1"]
  2925.                 .createInstance(Components.interfaces.nsITimer);
  2926.     observer.timer.initWithCallback(observer, promptWaitTime * 1000,
  2927.                                     observer.timer.TYPE_ONE_SHOT);
  2928.   },
  2929.  
  2930.   /**
  2931.    * Show the UI when the user was idle
  2932.    * @param   parent
  2933.    *          A parent window, can be null
  2934.    * @param   uri
  2935.    *          The URI string of the dialog to show
  2936.    * @param   name
  2937.    *          The Window Name of the dialog to show, in case it is already open
  2938.    *          and can merely be focused
  2939.    * @param   page
  2940.    *          The page of the wizard to be displayed, if one is already open.
  2941.    * @param   update
  2942.    *          An update to pass to the UI in the window arguments.
  2943.    *          Can be null
  2944.    */
  2945.   _showUIWhenIdle: function(parent, uri, features, name, page, update) {
  2946.     var idleService =
  2947.       Components.classes["@mozilla.org/widget/idleservice;1"]
  2948.                 .getService(Components.interfaces.nsIIdleService);
  2949.  
  2950.     const IDLE_TIME = getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60);
  2951.     if (idleService.idleTime / 1000 >= IDLE_TIME) {
  2952.       this._showUI(parent, uri, features, name, page, update);
  2953.     } else {
  2954.       var observerService =
  2955.         Components.classes["@mozilla.org/observer-service;1"]
  2956.                   .getService(Components.interfaces.nsIObserverService);
  2957.       var observer = {
  2958.         updatePrompt: this,
  2959.         observe: function (aSubject, aTopic, aData) {
  2960.           switch (aTopic) {
  2961.             case "idle":
  2962.               this.updatePrompt._showUI(parent, uri, features, name, page, update);
  2963.               // fall thru
  2964.             case "quit-application":
  2965.               idleService.removeIdleObserver(this, IDLE_TIME);
  2966.               observerService.removeObserver(this, "quit-application");
  2967.               break;
  2968.           }
  2969.         }
  2970.       };
  2971.       idleService.addIdleObserver(observer, IDLE_TIME);
  2972.       observerService.addObserver(observer, "quit-application", false);
  2973.     }
  2974.   },
  2975.  
  2976.   /**
  2977.    * Show the Update Checking UI
  2978.    * @param   parent
  2979.    *          A parent window, can be null
  2980.    * @param   uri
  2981.    *          The URI string of the dialog to show
  2982.    * @param   name
  2983.    *          The Window Name of the dialog to show, in case it is already open
  2984.    *          and can merely be focused
  2985.    * @param   page
  2986.    *          The page of the wizard to be displayed, if one is already open.
  2987.    * @param   update
  2988.    *          An update to pass to the UI in the window arguments.
  2989.    *          Can be null
  2990.    */
  2991.   _showUI: function(parent, uri, features, name, page, update) {
  2992.     var ary = null;
  2993.     if (update) {
  2994.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2995.                       .createInstance(Components.interfaces.nsISupportsArray);
  2996.       ary.AppendElement(update);
  2997.     }
  2998.  
  2999.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  3000.                        .getService(Components.interfaces.nsIWindowMediator);
  3001.     var win = wm.getMostRecentWindow(name);
  3002.     if (win) {
  3003.       if (page && "setCurrentPage" in win)
  3004.         win.setCurrentPage(page);
  3005.       win.focus();
  3006.     }
  3007.     else {
  3008.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  3009.       if (features)
  3010.         openFeatures += "," + features;
  3011.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  3012.                          .getService(Components.interfaces.nsIWindowWatcher);
  3013.       ww.openWindow(parent, uri, "", openFeatures, ary);
  3014.     }
  3015.   },
  3016.  
  3017.   /**
  3018.    * See nsISupports.idl
  3019.    */
  3020.   QueryInterface: function(iid) {
  3021.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  3022.         !iid.equals(Components.interfaces.nsISupports))
  3023.       throw Components.results.NS_ERROR_NO_INTERFACE;
  3024.     return this;
  3025.   }
  3026. };
  3027. //@line 3145 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3028.  
  3029. var gModule = {
  3030.   registerSelf: function(componentManager, fileSpec, location, type) {
  3031.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  3032.  
  3033.     for (var key in this._objects) {
  3034.       var obj = this._objects[key];
  3035.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  3036.                                                fileSpec, location, type);
  3037.     }
  3038.  
  3039.     // Make the Update Service a startup observer
  3040.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  3041.                                     .getService(Components.interfaces.nsICategoryManager);
  3042.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  3043.                                      "service," + this._objects.service.contractID,
  3044.                                      true, true);
  3045.   },
  3046.  
  3047.   getClassObject: function(componentManager, cid, iid) {
  3048.     if (!iid.equals(Components.interfaces.nsIFactory))
  3049.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  3050.  
  3051.     for (var key in this._objects) {
  3052.       if (cid.equals(this._objects[key].CID))
  3053.         return this._objects[key].factory;
  3054.     }
  3055.  
  3056.     throw Components.results.NS_ERROR_NO_INTERFACE;
  3057.   },
  3058.  
  3059.   _objects: {
  3060.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  3061.                contractID : "@mozilla.org/updates/update-service;1",
  3062.                className  : "Update Service",
  3063.                factory    : makeFactory(UpdateService)
  3064.              },
  3065.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  3066.                contractID : "@mozilla.org/updates/update-checker;1",
  3067.                className  : "Update Checker",
  3068.                factory    : makeFactory(Checker)
  3069.              },
  3070. //@line 3188 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3071.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  3072.                contractID : "@mozilla.org/updates/update-prompt;1",
  3073.                className  : "Update Prompt",
  3074.                factory    : makeFactory(UpdatePrompt)
  3075.              },
  3076. //@line 3194 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3077.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  3078.                contractID : "@mozilla.org/updates/timer-manager;1",
  3079.                className  : "Timer Manager",
  3080.                factory    : makeFactory(TimerManager)
  3081.              },
  3082.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  3083.                contractID : "@mozilla.org/updates/update-manager;1",
  3084.                className  : "Update Manager",
  3085.                factory    : makeFactory(UpdateManager)
  3086.              },
  3087.   },
  3088.  
  3089.   canUnload: function(componentManager) {
  3090.     return true;
  3091.   }
  3092. };
  3093.  
  3094. /**
  3095.  * Creates a factory for instances of an object created using the passed-in
  3096.  * constructor.
  3097.  */
  3098. function makeFactory(ctor) {
  3099.   function ci(outer, iid) {
  3100.     if (outer != null)
  3101.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  3102.     return (new ctor()).QueryInterface(iid);
  3103.   }
  3104.   return { createInstance: ci };
  3105. }
  3106.  
  3107. function NSGetModule(compMgr, fileSpec) {
  3108.   return gModule;
  3109. }
  3110.  
  3111. /**
  3112.  * Determines whether or there are installed addons which are incompatible
  3113.  * with this update.
  3114.  * @param   update
  3115.  *          The update to check compatibility against
  3116.  * @returns true if there are no addons installed that are incompatible with
  3117.  *          the specified update, false otherwise.
  3118.  */
  3119. function isCompatible(update) {
  3120. //@line 3238 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3121.   var em =
  3122.       Components.classes["@mozilla.org/extensions/manager;1"].
  3123.       getService(nsIExtensionManager);
  3124.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  3125.     update.platformVersion, nsIUpdateItem.TYPE_ANY, false, { });
  3126.   return items.length == 0;
  3127. //@line 3247 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3128. }
  3129.  
  3130. /**
  3131.  * Shows a prompt for an update, provided there are no incompatible addons.
  3132.  * If there are, kick off an update check and see if updates are available
  3133.  * that will resolve the incompatibilities.
  3134.  * @param   update
  3135.  *          The available update to show
  3136.  */
  3137. function showPromptIfNoIncompatibilities(update) {
  3138.   function showPrompt(update) {
  3139.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  3140.     var prompter =
  3141.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  3142.         createInstance(Components.interfaces.nsIUpdatePrompt);
  3143.     prompter.showUpdateAvailable(update);
  3144.   }
  3145.  
  3146. //@line 3266 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3147.   /**
  3148.    * Determines if an addon is compatible with a particular update.
  3149.    * @param   addon
  3150.    *          The addon to check
  3151.    * @param   version
  3152.    *          The extensionVersion of the update to check for compatibility
  3153.    *          against.
  3154.    * @returns true if the addon is compatible, false otherwise
  3155.    */
  3156.   function addonIsCompatible(addon, version) {
  3157.     var vc =
  3158.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  3159.         getService(Components.interfaces.nsIVersionComparator);
  3160.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  3161.            (vc.compare(version, addon.maxAppVersion) <= 0);
  3162.   }
  3163.  
  3164.   /**
  3165.    * An object implementing nsIAddonUpdateCheckListener that looks for
  3166.    * available updates to addons and if updates are found that will make the
  3167.    * user's installed addon set compatible with the update, suppresses the
  3168.    * prompt that would otherwise be shown.
  3169.    * @param   addons
  3170.    *          An array of incompatible addons that are installed.
  3171.    * @constructor
  3172.    */
  3173.   function Listener(addons) {
  3174.     this._addons = addons;
  3175.   }
  3176.   Listener.prototype = {
  3177.     _addons: null,
  3178.  
  3179.     /**
  3180.      * See nsIUpdateService.idl
  3181.      */
  3182.     onUpdateStarted: function() {
  3183.     },
  3184.     onUpdateEnded: function() {
  3185.       // There are still incompatibilities, even after an extension update
  3186.       // check to see if there were newer, compatible versions available, so
  3187.       // we have to prompt.
  3188.       //
  3189.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we
  3190.       // handle incompatibilities:
  3191.       // UPDATE_CHECK_NEWVERSION    We count both VersionInfo updates _and_
  3192.       //      NewerVersion updates against the list of incompatible addons
  3193.       //      installed - i.e. if Foo 1.2 is installed and it is incompatible
  3194.       //      with the update, and we find Foo 2.0 which is but which is not
  3195.       //      yet downloaded or installed, then we do NOT prompt because the
  3196.       //      user can download Foo 2.0 when they restart after the update
  3197.       //      during the mismatch checking UI. This is the default, since it
  3198.       //      suppresses most prompt dialogs.
  3199.       // UPDATE_CHECK_COMPATIBILITY    We count only VersionInfo updates
  3200.       //      against the list of incompatible addons installed - i.e. if the
  3201.       //      situation above with Foo 1.2 and available update to 2.0
  3202.       //      applies, we DO show the prompt since a download operation will
  3203.       //      be required after the update. This is not the default and is
  3204.       //      supplied only as a hidden option for those that want it.
  3205.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE,
  3206.                          nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  3207.       if ((mode == nsIExtensionManager.UPDATE_CHECK_NEWVERSION
  3208.            && this._addons.length) || !isCompatible(update))
  3209.         showPrompt(update);
  3210.     },
  3211.     onAddonUpdateStarted: function(addon) {
  3212.     },
  3213.     onAddonUpdateEnded: function(addon, status) {
  3214.       const Ci = Components.interfaces;
  3215.       if (status != Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE)
  3216.         return;
  3217.  
  3218.       var reqVersion = addon.targetAppID == TOOLKIT_ID ?
  3219.                        update.platformVersion :
  3220.                        update.extensionVersion;
  3221.       if (!addonIsCompatible(addon, reqVersion))
  3222.         return;
  3223.  
  3224.       for (var i = 0; i < this._addons.length; ++i) {
  3225.         if (this._addons[i] == addon) {
  3226.           this._addons.splice(i, 1);
  3227.           break;
  3228.         }
  3229.       }
  3230.     },
  3231.     /**
  3232.      * See nsISupports.idl
  3233.      */
  3234.     QueryInterface: function(iid) {
  3235.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  3236.           !iid.equals(Components.interfaces.nsISupports))
  3237.         throw Components.results.NS_ERROR_NO_INTERFACE;
  3238.       return this;
  3239.     }
  3240.   };
  3241.  
  3242.   if (!isCompatible(update)) {
  3243.     var em =
  3244.         Components.classes["@mozilla.org/extensions/manager;1"].
  3245.         getService(nsIExtensionManager);
  3246.     var items = em.getIncompatibleItemList("", update.extensionVersion,
  3247.       update.platformVersion, nsIUpdateItem.TYPE_ANY, false, { });
  3248.     var listener = new Listener(items);
  3249.     // See documentation on |mode| above.
  3250.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE,
  3251.                        nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  3252.     em.update([], 0, mode, listener);
  3253.   }
  3254.   else
  3255. //@line 3375 "/build/buildd/xulrunner-1.9-1.9.0.14+build2+nobinonly/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3256.     showPrompt(update);
  3257. }
  3258.